package com.icinfo.cloud.provider.punish.common.documentoperate.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.icinfo.cloud.common.core.config.CfRedisRepository;
import com.icinfo.cloud.common.core.config.RedisRepository;
import com.icinfo.cloud.common.security.util.UserUtil;
import com.icinfo.cloud.provider.common.annotation.CaseChangeReportData;
import com.icinfo.cloud.provider.common.constant.Constant;
import com.icinfo.cloud.provider.common.enums.*;
import com.icinfo.cloud.provider.common.exception.BusinessException;
import com.icinfo.cloud.provider.common.utils.*;
import com.icinfo.cloud.provider.logs.model.LogsCaseDocumentSerialRecord;
import com.icinfo.cloud.provider.logs.service.ILogsCaseDocumentSerialRecordService;
import com.icinfo.cloud.provider.peripheralinterface.xfjdzf.dto.XfjdzfDocumentNumberInfoDto;
import com.icinfo.cloud.provider.peripheralinterface.xfjdzf.service.IXfjdzfInterfaceService;
import com.icinfo.cloud.provider.peripheralinterface.xzzf.service.IXzzfInterfaceService;
import com.icinfo.cloud.provider.punish.actscode.dto.ActsCodeDto;
import com.icinfo.cloud.provider.punish.actscode.service.ICaseActsCodeInfoService;
import com.icinfo.cloud.provider.punish.app.mapper.AppCaseBeforeDocumentRecordMapper;
import com.icinfo.cloud.provider.punish.app.model.AppCaseBeforeDocumentRecord;
import com.icinfo.cloud.provider.punish.approval.service.impl.CaseApprovalWaitRecordServiceImpl;
import com.icinfo.cloud.provider.punish.approval.vo.LineTerritoryInfoVo;
import com.icinfo.cloud.provider.punish.common.caseregister.service.IRegisterCommonService;
import com.icinfo.cloud.provider.punish.common.csourcedocumentoperate.service.ICSourceDocCommonOperateService;
import com.icinfo.cloud.provider.punish.common.documentoperate.dto.*;
import com.icinfo.cloud.provider.punish.common.documentoperate.enums.DocumentRecordStatusEnum;
import com.icinfo.cloud.provider.punish.common.documentoperate.enums.DocumentStatusEnum;
import com.icinfo.cloud.provider.punish.common.documentoperate.mapper.StageDocCommonOperateMapper;
import com.icinfo.cloud.provider.punish.common.documentoperate.service.IStageDocCommonOperateService;
import com.icinfo.cloud.provider.punish.common.documentoperate.vo.CorrectionDocSaveVo;
import com.icinfo.cloud.provider.punish.common.documentoperate.vo.DocumentCommonFormDataVo;
import com.icinfo.cloud.provider.punish.common.documentoperate.vo.DocumentCommonFormHtmlVo;
import com.icinfo.cloud.provider.punish.common.nonlitigation.dto.CaseNonLitigationExecuteRequestDto;
import com.icinfo.cloud.provider.punish.common.nonlitigation.service.ICaseNonLitigationExecuteRecordService;
import com.icinfo.cloud.provider.punish.common.publicity.dto.PublicityModifyRecordSaveDto;
import com.icinfo.cloud.provider.punish.common.publicity.enums.CasePublicityModifyEnum;
import com.icinfo.cloud.provider.punish.common.publicity.model.CasePublicityModifyRecord;
import com.icinfo.cloud.provider.punish.common.publicity.service.ICasePublicityModifyRecordService;
import com.icinfo.cloud.provider.punish.common.seal.dto.FileSealInfoQueryDto;
import com.icinfo.cloud.provider.punish.common.seal.service.IFileSealProvinceUnifiedService;
import com.icinfo.cloud.provider.punish.config.dto.RelationWorkflowInfoRequest;
import com.icinfo.cloud.provider.punish.config.mapper.ConfigBusiParamDocumentColumnMapper;
import com.icinfo.cloud.provider.punish.config.mapper.ConfigDictionaryInfoMapper;
import com.icinfo.cloud.provider.punish.config.mapper.SysDepartParamMapper;
import com.icinfo.cloud.provider.punish.config.model.*;
import com.icinfo.cloud.provider.punish.config.service.IConfigBusiParamDeptService;
import com.icinfo.cloud.provider.punish.config.service.IConfigBusiParamDocumentInfoService;
import com.icinfo.cloud.provider.punish.config.service.IConfigBusiParamMainService;
import com.icinfo.cloud.provider.punish.config.service.ISysDepartParamService;
import com.icinfo.cloud.provider.punish.config.vo.BusiTableOperateVo;
import com.icinfo.cloud.provider.punish.csource.manage.mapper.CaseSourceDocumentRecordMapper;
import com.icinfo.cloud.provider.punish.csource.manage.model.CaseSourceDocumentRecord;
import com.icinfo.cloud.provider.punish.evideinv.service.EvidenceInventoryService;
import com.icinfo.cloud.provider.punish.ucase.caseadditional.model.CaseAdditionalRecord;
import com.icinfo.cloud.provider.punish.ucase.caseadditional.service.ICaseAdditionalRecordService;
import com.icinfo.cloud.provider.punish.ucase.casemain.dto.CaseDocumentRecordDto;
import com.icinfo.cloud.provider.punish.ucase.casemain.dto.CasePartyRecordAdjustSaveDto;
import com.icinfo.cloud.provider.punish.ucase.casemain.dto.PunishMsgParams;
import com.icinfo.cloud.provider.punish.ucase.casemain.enums.*;
import com.icinfo.cloud.provider.punish.ucase.casemain.mapper.*;
import com.icinfo.cloud.provider.punish.ucase.casemain.model.*;
import com.icinfo.cloud.provider.punish.ucase.casemain.service.*;
import com.icinfo.cloud.provider.punish.ucase.casemain.vo.*;
import com.icinfo.cloud.provider.punish.ucase.investigateevidence.dto.CaseOperateUpdateDto;
import com.icinfo.cloud.provider.punish.ucase.investigateevidence.dto.CaseStatusUpdateAfterApprovalDto;
import com.icinfo.cloud.provider.punish.ucase.investigateevidence.enums.CaseStatusChangeEffectEnum;
import com.icinfo.cloud.provider.punish.ucase.investigateevidence.enums.CaseStatusChangeTypeEnum;
import com.icinfo.cloud.provider.punish.ucase.investigateevidence.mapper.CaseDocumentAuthedEntrustMapper;
import com.icinfo.cloud.provider.punish.ucase.investigateevidence.mapper.CaseDocumentSendinfoConfirmMapper;
import com.icinfo.cloud.provider.punish.ucase.investigateevidence.model.CaseDocumentAuthedEntrust;
import com.icinfo.cloud.provider.punish.ucase.investigateevidence.model.CaseDocumentSendinfoConfirm;
import com.icinfo.cloud.provider.punish.ucase.payment.enums.PayWayEnum;
import com.icinfo.cloud.provider.punish.ucase.payment.service.ICasePaymentMainRecordService;
import com.icinfo.cloud.provider.punish.ucase.punishdecide.service.IPunishDecideService;
import com.icinfo.cloud.provider.punish.ucaseassist.assistmain.model.CaseAssistMainInfo;
import com.icinfo.cloud.provider.punish.ucaseassist.assistmain.service.ICaseAssistMainInfoService;
import com.icinfo.cloud.workflow.common.annotation.WorkFlowRollAnnotation;
import com.icinfo.cloud.workflow.config.model.ConfigWorkFlowDocument;
import com.icinfo.cloud.workflow.config.service.IConfigWorkFlowDocumentService;
import com.icinfo.cloud.workflow.work.model.WorkFlowRollSubMainInfo;
import com.icinfo.cloud.workflow.work.service.IWorkFlowRollSubMainInfoService;
import com.icinfo.cloud.xzcf.provider.member.line.dto.LineDTO;
import com.icinfo.cloud.xzcf.provider.member.userinfo.dto.UserDTO;
import com.icinfo.framework.common.web.Result;
import com.icinfo.framework.mybatis.mapper.entity.Example;
import com.icinfo.framework.tools.utils.DateUtils;
import com.icinfo.framework.tools.utils.MapUtils;
import com.icinfo.framework.tools.utils.StringUtils;
import com.timevale.tgtext.text.pdf.PdfReader;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * 描述：文书阶段公共操作接口事先类
 *
 * @author xiangyuyu
 * @date 2022/2/16 21:07
 */
@Service
@Slf4j
public class StageDocCommonOperateServiceImpl implements IStageDocCommonOperateService {
    @Value("${document.url}")
    private String url;
    @Value("${document.api.templateDetail}")
    private String templateDetail;
    @Value("${document.api.uploadConvertedPdf}")
    private String uploadConvertedPdf;
    @Value("${document.api.uploadBase64File}")
    private String uploadBase64File;
    @Value("${actionCode.isEnable}")
    private String isEnable;
    @Resource
    IConfigBusiParamDocumentInfoService configBusiParamDocumentInfoService;
    @Autowired
    private ICaseHandlePersonRecordService caseHandlePersonRecordService;
    @Autowired
    private IConfigBusiParamDeptService configBusiParamDeptService;
    @Resource
    private StageDocCommonOperateMapper stageDocCommonOperateMapper;
    @Resource
    private IFileSealProvinceUnifiedService fileSealProvinceUnifiedService;

    @Autowired
    private ICaseDocumentNumberSerialService caseDocumentNumberSerialService;
    @Resource
    private ICasePaymentMainRecordService iCasePaymentMainRecordService;
    @Resource
    ICaseTemporaryRecordService caseTemporaryRecordService;
    @Resource
    ICasePublicityModifyRecordService casePublicityModifyRecordService;
    /**
     * redis repository
     */
    @Autowired
    private RedisRepository redisRepository;

    @Autowired
    private CaseDocumentRecordMapper caseDocumentRecordMapper;
    @Autowired
    private ConfigBusiParamDocumentColumnMapper configBusiParamDocumentColumnMapper;
    @Autowired
    private CaseMainInfoMapper caseMainInfoMapper;
    @Resource
    ICaseDocumentRecordService caseDocumentRecordService;
    @Autowired
    private CaseDocumentRecordHisMapper caseDocumentRecordHisMapper;
    @Autowired
    private ICasePartiesRecordService casePartiesRecordService;
    @Resource
    private IPunishDecideService iPunishDecideService;
    @Autowired
    private ISysDepartParamService sysDepartParamService;
    @Resource
    private ICaseNonLitigationExecuteRecordService caseNonLitigationExecuteRecordService;
    @Resource
    private CaseMainDetailInfoMapper caseMainDetailInfoMapper;

    @Resource
    private EvidenceInventoryService evidenceInventoryService;
    @Resource
    private ICaseMainInfoService caseMainInfoService;

    @Resource
    private ICaseMainInfoStatusChangeRecordService caseMainInfoStatusChangeRecordService;

    @Resource
    private ICaseMainDetailSimpleInfoService caseMainDetailSimpleInfoService;
    @Autowired
    private IWorkFlowRollSubMainInfoService workFlowRollSubMainInfoService;
    @Resource
    private CaseMainDetailSimpleInfoMapper caseMainDetailSimpleInfoMapper;
    /**
     * 送达关联且需要当事人id的文书种类编码列表
     */
    public static List<String> sentRelatedNeedPartyIdDocumentKindCodeList;
    @Resource
    private ICaseMainDetailAuxiliaryInfoService caseMainDetailAuxiliaryInfoService;
    @Resource
    private ICasePunishDecisionRevokeRecordService casePunishDecisionRevokeRecordService;

    @Autowired
    private IConfigWorkFlowDocumentService configWorkFlowDocumentService;

    @Resource
    private CaseAppendixRecordMapper caseAppendixRecordMapper;
    @Autowired
    private ICaseAssistMainInfoService caseAssistMainInfoService;
    @Resource
    private CaseDocumentSendinfoConfirmMapper caseDocumentSendinfoConfirmMapper;
    @Resource
    private AppCaseBeforeDocumentRecordMapper appCaseBeforeDocumentRecordMapper;
    @Resource
    private ICaseActsCodeInfoService caseActsCodeInfoService;
    @Resource
    private CasePartiesRecordMapper casePartiesRecordMapper;
    @Resource
    private CaseApprovalWaitRecordServiceImpl caseApprovalWaitRecordService;
    @Resource
    private IXzzfInterfaceService xzzfInterfaceService;
    @Resource
    private ICaseAdditionalRecordService caseAdditionalRecordService;
    @Resource
    private CaseReasonMainRecordMapper caseReasonMainRecordMapper;

    static {
        sentRelatedNeedPartyIdDocumentKindCodeList = new ArrayList<>();
        sentRelatedNeedPartyIdDocumentKindCodeList.add(Constant.STRING_KIND_CODE_SDHZ);
        sentRelatedNeedPartyIdDocumentKindCodeList.add(Constant.STRING_KIND_CODE_ZXQKHCJL);
        sentRelatedNeedPartyIdDocumentKindCodeList.add(Constant.STRING_KIND_CODE_XWTZS);
        sentRelatedNeedPartyIdDocumentKindCodeList.add(Constant.STRING_KIND_CODE_SQWTS);
        sentRelatedNeedPartyIdDocumentKindCodeList.add(Constant.STRING_KIND_CODE_SDDZQRS);
    }

    @Resource
    private IXfjdzfInterfaceService xfjdzfInterfaceService;
    @Resource
    private CaseSourceDocumentRecordMapper caseSourceDocumentRecordMapper;
    @Resource
    private ICSourceDocCommonOperateService sourceDocCommonOperateService;
    @Resource
    private CaseDocumentAuthedEntrustMapper caseDocumentAuthedEntrustMapper;
    @Resource
    private SysDepartParamMapper sysDepartParamMapper;
    @Resource
    private CaseMainDetailAuxiliaryInfoMapper caseMainDetailAuxiliaryInfoMapper;
    @Resource
    private CfRedisRepository cfRedisRepository;
    @Resource
    private ICaseInfoAdjustRecordService caseInfoAdjustRecordService;
    @Resource
    private IRegisterCommonService registerCommonService;
    @Resource
    private IConfigBusiParamMainService configBusiParamMainService;
    @Resource
    private ConfigDictionaryInfoMapper configDictionaryInfoMapper;
    @Resource
    private ILogsCaseDocumentSerialRecordService logsCaseDocumentSerialRecordService;

    /**
     * 保存文书信息通用接口  TODO 必须优化
     *
     * @param saveDto
     * @return {@link boolean}
     * @author liyafeng
     * @date 2022/2/27
     */
    @Override
    @Transactional(rollbackFor = {Error.class, Exception.class})
    @WorkFlowRollAnnotation
    @CaseChangeReportData
    public Map<String, Object> saveDocInfo(StageDocCommonOperateSaveDto saveDto) {
        String caseId = saveDto.getCaseId();
//        String serialCatalogCode = "";
        List<Map<String, Object>> docNumberList = new ArrayList<>();
        Map<String, Object> resultMap = new HashMap<>();
        try {
            CaseMainInfo caseMainInfo = caseMainInfoMapper.selectByPrimaryKey(caseId);

            String handleType = caseMainInfo.getHandleType();
            String casePartiesReasonType = caseMainInfo.getCasePartiesReasonType();
            String documentCatalogCode = saveDto.getDocumentCatalogCode();
            String partyId = saveDto.getPartyId();
            //查询文书配置信息
            ConfigBusiParamDocumentInfo configBusiParamDocumentInfo = configBusiParamDocumentInfoService.getDetailByDocumentCatalogCode(saveDto.getDocumentCatalogCode());
            String documentKindCode = configBusiParamDocumentInfo.getDocumentKindCode();
            saveDto.setDocumentKindCode(documentKindCode);
            //处理特殊文书
            dealSpecialDocument(saveDto);

            CaseMainInfoVo caseMainInfoVo = new CaseMainInfoVo();
            BeanUtils.copyProperties(caseMainInfo, caseMainInfoVo);
            //获取案件信息
            if (caseMainInfoService.validateCaseIsInNotDealStatus(caseMainInfoVo, null)
                    && !caseMainInfoService.validateIsTerminateCaseWhenBreakOff(caseMainInfoVo, null, documentKindCode)) {
                //如果存在行政处罚撤销决定书，可以送达
                CaseDocumentRecordDto documentInfo = caseDocumentRecordService.getCaseDocumentRecordByKindCode(caseId, Constant.STRING_KIND_CODE_XZCFCXJDS);
                if (ObjectUtils.isEmpty(documentInfo)) {
                    throw new BusinessException("当前案件状态不允许进行该操作");
                }
            }
            //String isShowPartiesSelector = caseMainInfoService.validateIsShowPartiesSelector(caseMainInfoVo, null);
            if (ObjectUtils.isEmpty(partyId)) {
                String caseFlowCode = caseMainInfo.getCaseFlowCode();
                String caseFlowVersion = caseMainInfo.getCaseFlowVersion();
                if (ObjectUtils.isEmpty(caseFlowCode)) {
                    caseFlowCode = "-";
                }
                if (ObjectUtils.isEmpty(caseFlowVersion)) {
                    caseFlowVersion = "-";
                }
                List<ConfigWorkFlowDocument> configWorkFlowDocumentList = configWorkFlowDocumentService.getConfigWorkFlowDocumentByWorkFLowAndCatalogCode(caseFlowCode, caseFlowVersion, caseMainInfo.getCaseCurrentLinkCode(), documentCatalogCode);
                if (configWorkFlowDocumentList.size() > 0) {
                    if (Constant.STRING_2.equals(configWorkFlowDocumentList.get(0).getRelatedHolderType())
                            && HandleTypeEnum.PART_PUNISH.getCode().equals(handleType)) {
                        throw new BusinessException("多当事人分别处罚时请指定当事人id");
                    }
                /*if (YesOrNoEnum.YES.getCode().equals(isShowPartiesSelector) &&
                        !CaseStatusChangeTypeEnum.isCaseChangeDocEnum(documentKindCode)) {
                    throw new BusinessException("多当事人分别处罚时请指定当事人id");
                }
                //多当事人，填写时例外 fixme:后期文书目录编码判断可优化成从数据库读取
                if (PartiesReasonTypeEnum.MULTIPLE_PARTIES.getCode().equals(casePartiesReasonType)
                        && "SDDZQRS6486A".equals(documentCatalogCode)) {
                    throw new BusinessException("多当事人时请指定当事人id");
                }*/
                    Map<String, String> map = casePartiesRecordService.getCasePartyIdNameInfo(caseId);
                    partyId = map.get("partyId");
                } else if (CaseTypeEnum.SIMPLE_PROCEDURE.getCode().equals(caseMainInfo.getCaseType())) {
                    Map<String, String> map = casePartiesRecordService.getCasePartyIdNameInfo(caseId);
                    partyId = map.get("partyId");
                } else if (CaseTypeEnum.SIMPLE_QUICK.getCode().equals(caseMainInfo.getCaseType())
                        && (Constant.STRING_KIND_CODE_DK2SJCXGZS.equals(documentKindCode) || Constant.STRING_KIND_CODE_CFJDS.equals(documentKindCode) || Constant.STRING_KIND_CODE_DK2JAKBTZS.equals(documentKindCode))) {
                    Map<String, String> map = casePartiesRecordService.getCasePartyIdNameInfo(caseId);
                    partyId = map.get("partyId");
                }
            }


//            Map<String, Object> resultMap = new HashMap<>();
            String documentLinkObjectType = configBusiParamDocumentInfo.getDocumentLinkObjectType();
            //分别处罚与当事人关联的文书
            if (Constant.STRING_2.equals(handleType) && Constant.STRING_2.equals(documentLinkObjectType)) {
                resultMap.put("workSubId", saveDto.getPartyId());
            }
            //重新赋值
            saveDto.setPartyId(partyId);
            int num = 0;
            String documentId = "";
            resultMap.put("success", "true");
            //根据文书目录编码获取模板code
            String templateCode = saveDto.getDocumentTemplateCode();
            if (ObjectUtil.isEmpty(templateCode)) {
                templateCode = getTemplateCodeByDocumentCatalogCode(saveDto.getDocumentCatalogCode(), caseId, saveDto.getDataMap(), partyId);
            }
            //处理参数
            saveDto.setDocumentTemplateCode(templateCode);
            Map<String, Object> paramMap = dealDocParamMap(saveDto, templateCode);
            long start = System.currentTimeMillis();
            System.out.println("文书生成开始----------------------------------" + start);
            //文号生成;1.判断文号是否已生成 2.未生成则 判断文号生成配置，审批前生成在此处生成，审批后生成在审批完成后生成
            //外部系统对接时使用对应系统文号
            Map<String, Object> docNumberMap = new HashMap<>();
            String documentNumber = "";



        /*try {

        }catch (Exception e){
            //如果是立案审批表，且文号已经产生的情况下
            if(DocumentKindEnum.DOC_KIND_LASPB.equals(documentKindCode) && StringUtils.isNotBlank(documentNumber)){
                cfRedisRepository.leftPush("",);
            }

        }*/


            String caseOrgCode = caseMainInfo.getCaseOrgCode();
            Object dataSource = saveDto.getDataMap().get("DATA_SOURCE");
            if (DocumentKindEnum.DOC_KIND_JYCXCFJDS.getCode().equals(documentKindCode)
                    && !ObjectUtils.isEmpty(dataSource) && ApiVisitDataSourceEnum.ZJSXFJDZFXT_MOBILE.getId().equals((String) dataSource)) {
                //获取外部系统文号
                XfjdzfDocumentNumberInfoDto dto = new XfjdzfDocumentNumberInfoDto(caseOrgCode, DocumentKindEnum.DOC_KIND_JYCXCFJDS.getCode());
                documentNumber = xfjdzfInterfaceService.getDocumentNumber(dto);
            } else if (!DocumentKindEnum.DOC_KIND_JYCXCFJDS.getCode().equals(documentKindCode) &&
                    !DocumentKindEnum.DOC_KIND_JYCXGAWTCFJDS.getCode().equals(documentKindCode)) {
                //简易程序处罚决定书与公安委托执法处罚决定书第一次生成不生成文号
                Map<String, Object> docNumberResultMap = genDocumentNumber(documentCatalogCode, saveDto, configBusiParamDocumentInfo);
                documentNumber =MapUtils.getString(docNumberResultMap,"documentNumber","");
                if(docNumberResultMap.containsKey("serialNumber")){
                    docNumberMap.put("serialNumber",docNumberResultMap.get("serialNumber"));
                    docNumberMap.put("serialCatalogCode",documentCatalogCode);
                    docNumberList.add(docNumberMap);
                    if (ObjectUtil.isNotEmpty(saveDto.getExceptionCaseDocumentSerialKey())) {
                        //审批调用, 则把文号数据存入redis, 用于审批异常文号回归
                        String exceptionSerialStr = JSON.toJSONString(docNumberList);
                        //将缓存加入线程上下文
                        BusinessContextUtil.set(BusinessContextKeyEnum.DOCUMENT_NUMBER_REGRESSION_IDENTIFICATION_CODE, exceptionSerialStr);
//                        cfRedisRepository.setExpire(saveDto.getExceptionCaseDocumentSerialKey(), exceptionSerialStr, 10 * 60);
                    }
                }
            }
            paramMap.put("documentNumber", documentNumber);

            //简易程序处罚决定书文号更新至简易案件详情表
        /*if (!ObjectUtils.isEmpty(documentNumber) && DocumentKindEnum.DOC_KIND_JYCXCFJDS.getCode().equals(documentKindCode)) {
            CaseMainDetailSimpleInfo caseMainDetailSimpleInfo = caseMainDetailSimpleInfoService.getCaseMainDetailSimpleInfo(caseId);
            caseMainDetailSimpleInfo.setPunishDocumentNumber(documentNumber);
            caseMainDetailSimpleInfoMapper.updateByPrimaryKeySelective(caseMainDetailSimpleInfo);
            Example example = new Example(CaseMainDetailAuxiliaryInfo.class);
            example.createCriteria().andEqualTo("caseId", saveDto.getCaseId());
            List<CaseMainDetailAuxiliaryInfo> caseMainDetailAuxiliaryInfos = caseMainDetailAuxiliaryInfoMapper.selectByExample(example);
            if (!ObjectUtils.isEmpty(caseMainDetailAuxiliaryInfos)) {
                for (CaseMainDetailAuxiliaryInfo caseMainDetailAuxiliaryInfo : caseMainDetailAuxiliaryInfos) {
                    CaseMainDetailAuxiliaryInfo updateCaseMainDetailAuxiliaryInfo = new CaseMainDetailAuxiliaryInfo();
                    updateCaseMainDetailAuxiliaryInfo.setId(caseMainDetailAuxiliaryInfo.getId());
                    updateCaseMainDetailAuxiliaryInfo.setPunishDocumentNumber(documentNumber);
                    caseMainDetailAuxiliaryInfoMapper.updateByPrimaryKeySelective(updateCaseMainDetailAuxiliaryInfo);
                }
            }
            //调用行政行为码赋码接口 同时生成二维码 与 条形码
            //改为在app调用生成服务
            try {
                UserDTO userDTO = UserUtil.getUserInfo();
                String areaCode = userDTO.getAreaCode();
                ActsCodeDto actsCodeDto = new ActsCodeDto();
                actsCodeDto.setCaseId(caseId);
                caseActsCodeInfoService.saveCaseActsCodeInfo(actsCodeDto);
            } catch (Exception e) {
                e.printStackTrace();
            }

        }*/
            //计算送达期限
            String isSend = configBusiParamDocumentInfo.getIsSend();
            String isApprove = configBusiParamDocumentInfo.getIsApprove();
            LocalDate sentDeadLine = null;
            //需要送达不需要审批的文书计算送达期限
            if (YesOrNoEnum.YES.getCode().equals(isSend)
                    && !YesOrNoEnum.YES.getCode().equals(isApprove)) {
                Integer limitDay = configBusiParamDocumentInfo.getSendLimitDay();
                String limitDayType = configBusiParamDocumentInfo.getSendLimitType();
                sentDeadLine = caseDocumentRecordService.calculateSentDeadLine(caseId, documentCatalogCode, limitDay, limitDayType, false);
                if (ObjectUtils.isEmpty(sentDeadLine)) {
                    throw new BusinessException("未获取到文书送达期限-caseId:" + caseId + ",documentCatalogCode:" + documentCatalogCode);
                }
            }

            //新增: 简易程序处罚决定书处理逻辑： 自行缴纳的，生成支付二维码；当场收缴的不生成支付二维码
            //处罚决定书时获取缴费二维码
            if (StringUtils.equalsAny(configBusiParamDocumentInfo.getDocumentKindCode(), Constant.STRING_KIND_CODE_CFJDS)
                    || DocumentKindEnum.DOC_KIND_JYCXCFJDS.getCode().equals(configBusiParamDocumentInfo.getDocumentKindCode())
                    || DocumentKindEnum.DOC_KIND_JYCXGAWTCFJDS.getCode().equals(configBusiParamDocumentInfo.getDocumentKindCode())) {
                boolean isCreate = true;
                String caseType = caseMainInfo.getCaseType();
                if (CaseTypeEnum.SIMPLE_PROCEDURE.getCode().equals(caseType)) {
                    //简易处罚,查询缴款方式
                    CaseMainDetailSimpleInfo simpleInfo = caseMainDetailSimpleInfoService.getCaseMainDetailSimpleInfo(caseId);
                    if (ObjectUtils.isEmpty(simpleInfo) || !simpleInfo.getPunishKinds().contains("罚款") || PayWayEnum.ON_SITE.getCode().equals(simpleInfo.getPayWay())) {
                        //当场收缴的、处罚不包括罚款的不生成支付二维码
                        isCreate = false;
                    }
                    if (DocumentKindEnum.DOC_KIND_JYCXGAWTCFJDS.getCode().equals(documentKindCode)){
                        // 简易处罚-公安委托执法时不生成缴款单
                        isCreate = false;
                    }
                    // 暂存时不生成真正二维码
                    if (isCreate && CaseStatusEnum.TEMP.getCode().equals(caseMainInfo.getCaseStatus())) {
                        List payInfoList = new ArrayList();
                        paramMap.put("qrBase64", Constant.INVALID_QR_CODE_URL);
                        paramMap.put("paymentQRCodeContent", "缴款二维码：");
                        //定义组织和部门code
                        String orgCode = caseMainInfo.getCaseOrgCode();
                        String deptCode = caseMainInfo.getCaseDeptCode();
                        //获取委托组织code
                        String clientOrgCode = getEntrustClientOrgCodeIfExists(caseId, caseMainInfo);
                        if (StrUtil.isNotEmpty(clientOrgCode)) {
                            orgCode = clientOrgCode;
                            deptCode = null;
                        }
                        SysDepartParam sysDepartParam = sysDepartParamService.getSysDepartParamByOrgCodeAndDeptCode(orgCode, deptCode);
                        Map<String, String> payInfoMap = new HashMap<>(2);
                        payInfoMap.put("XZCFJDS_JNFKD", sysDepartParam.getPayBankName());
                        payInfoMap.put("XZCFJDS_SKZH", "（户名：" + sysDepartParam.getPayBankAccountName() + "，账号：" + sysDepartParam.getPayBankAccount() + "）");
                        payInfoList.add(payInfoMap);
                        paramMap.put("punishKindCheckPayInfo", payInfoList);
                        isCreate = false;
                    }
                }

                if (isCreate) {
                    //生成缴款单信息
                    String paymentSlipNumber = iCasePaymentMainRecordService.saveCasePaymentMainRecord(caseId, documentCatalogCode, partyId, caseType);
                    System.out.println("生成缴款单信息耗时------------------------" + (System.currentTimeMillis() - start));
                    if (!ObjectUtils.isEmpty(paymentSlipNumber)) {
                        //获取缴款单二维码信息等
                        Map<String, String> paymentInfo = iPunishDecideService.getPaymentInfo(paymentSlipNumber);
                        System.out.println("获取缴款单二维码信息等耗时------------------------" + (System.currentTimeMillis() - start));
                        //paramMap.put("qrBase64", paymentInfo.get("qrBase64"));
                        //base64优化成地址
                        paramMap.put("qrBase64", paymentInfo.get("qrBase64"));
                        paramMap.put("XZCFJDS_JKDH", paymentSlipNumber);
                        List payInfoList = new ArrayList();
                        Map<String, String> payInfoMap = new HashMap<>(2);
                        payInfoMap.put("XZCFJDS_JKDH", paymentSlipNumber);
                        //payInfoMap.put("qrBase64", paymentInfo.get("qrBase64"));
                        //base64优化成地址
                        payInfoMap.put("qrBase64", paymentInfo.get("qrBase64"));
                        payInfoList.add(payInfoMap);
                        paramMap.put("punishKindCheckPayInfo", payInfoList);
                    }
                }


            }
            // 处理案件操作变更
            //根据条件添加签章时间
            if ("1".equals(configBusiParamDocumentInfo.getIsDeptSign())) {
                if (("CLOSE-TRIGGER-APPROVAL-PASS".equals(saveDto.getCloseSignal()) && "1".equals(configBusiParamDocumentInfo.getIsApprove())) || !"1".equals(configBusiParamDocumentInfo.getIsApprove())) {
                    paramMap.put("sealDate", DateUtils.formatDate(new Date(), "yyyy年M月d日"));
                }
            }
            //案件操作变更
            if (("CLOSE-TRIGGER-APPROVAL-PASS".equals(saveDto.getCloseSignal()) && "1".equals(configBusiParamDocumentInfo.getIsApprove())) || !"1".equals(configBusiParamDocumentInfo.getIsApprove())) {
                if (CaseStatusChangeTypeEnum.isCaseChangeDocEnum(documentKindCode)) {
                    CaseStatusUpdateAfterApprovalDto approvalDto = new CaseStatusUpdateAfterApprovalDto();
                    approvalDto.setCaseId(saveDto.getCaseId());
                    approvalDto.setDocumentKindCode(documentKindCode);
                    approvalDto.setCaseOperateType(CaseStatusChangeTypeEnum.getEnumByDocumentKindCode(documentKindCode).getCode());
                    caseMainInfoStatusChangeRecordService.updateCaseStatusAfterLastApproval(approvalDto);
                    // 处理延期时长
                    if (CaseStatusChangeTypeEnum.POSTPONE.getDocumentKindCode().equals(documentKindCode)) {
                        Integer casePostponeDay = Integer.valueOf(saveDto.getDataMap().get(Constant.CASE_POSTPONE_DAY).toString());
                        LocalDateTime postponeDate = caseMainInfo.getCaseTimelimit().plusDays(casePostponeDay);
                        String postponeLimitDate = postponeDate.toLocalDate().format(DateTimeFormatter.ofPattern("yyyy年MM月dd日"));
                        paramMap.put("postponeLimitDate", postponeLimitDate);
                    }
                }
            }
            //生成未签章文书
            String areaCode = "";
            try {
                UserDTO userDTO = UserUtil.getUserInfo();
                areaCode = userDTO.getAreaCode();
            } catch (Exception e) {
                e.printStackTrace();
            }
            FillAndConvertToPdfRequest pdfRequest = new FillAndConvertToPdfRequest();
            List<ConfigBusiParamDocumentInfo> configBusiParamDocumentInfos = configBusiParamDocumentInfoService.getDocumentConfigInfoByDocumentCatalogCode(saveDto.getCaseId(), caseMainInfoVo, saveDto.getDocumentCatalogCode());
            if (!ObjectUtils.isEmpty(configBusiParamDocumentInfos)) {
                ConfigBusiParamDocumentInfo configParamDocumentInfo = configBusiParamDocumentInfos.get(0);
                //行政行为二维码条形码添加
                if (Constant.STRING_1.equals(configParamDocumentInfo.getIsWatermark()) && Constant.STRING_TRUE.equals(isEnable)) {
                    //if (Constant.STRING_1.equals(configParamDocumentInfo.getIsWatermark())&&Constant.STRING_TRUE.equals(isEnable)&&TerritoryCodeEnum.ZHZF.getCode().equals(caseMainInfoVo.getCaseTerritoryCode())) {
                    boolean isWatermak = true;
                    //立案审批表最后一次审批添加水印
                    if (DocumentKindEnum.DOC_KIND_LASPB.getCode().equals(documentKindCode) && !"CLOSE-TRIGGER-APPROVAL-PASS".equals(saveDto.getCloseSignal())) {
                        isWatermak = false;
                    }
                    if (DocumentKindEnum.DOC_KIND_JYCXCFJDS.getCode().equals(documentKindCode)) {
                        CaseMainInfo caseMainInfoNew = caseMainInfoMapper.selectByPrimaryKey(caseId);
                        BeanUtils.copyProperties(caseMainInfoNew, caseMainInfoVo);
                    }
                    if (isWatermak) {
                        HashMap<String, Object> dataMap = saveDto.getDataMap();
                        dataMap.put("qrCodeUrl", caseMainInfoVo.getCaseQrCodeUrl());
                        dataMap.put("barCodeUrl", caseMainInfoVo.getCaseBarCodeUrl());
                        saveDto.setDataMap(dataMap);
                        pdfRequest.setIsWatermark(Constant.STRING_1);
                        pdfRequest.setWatermarkContent(caseMainInfoVo.getCaseActsCode());
                    }
                }
            }
            pdfRequest.setTemplateCode(templateCode);
            pdfRequest.setParamMap(saveDto.getDataMap());
            //判断文书模板类型是否为窄幅
            if (DocumentTemplateTypeEnum.NARROW_TEMPLATE.getCode().equals(saveDto.getDocumentTemplateType())) {
                pdfRequest.setTemplateType(DocumentTemplateKindEnum.NARROW_TEMPLATE.getCode());
            }
            //简易处罚决定书和公安委托执法处罚决定书设置模板类型为窄幅
            if (DocumentKindEnum.DOC_KIND_JYCXCFJDS.getCode().equals(documentKindCode) ||
                    DocumentKindEnum.DOC_KIND_JYCXGAWTCFJDS.getCode().equals(documentKindCode)) {
                pdfRequest.setTemplateType(DocumentTemplateKindEnum.NARROW_TEMPLATE.getCode());
            }
            Map<String, String> pdfUrl = getConvertedPdfUrl(pdfRequest);
            System.out.println("生成未签章文书耗时------------------------" + (System.currentTimeMillis() - start));
            if (ObjectUtil.isEmpty(pdfUrl)) {
                resultMap.put("success", "false");
                resultMap.put("msg", "文书生成失败！");
                return resultMap;
            }
            //判断是否需要签章
            String pdfSealUrl = "";
            String isGetBlankDoc = saveDto.getIsGetBlankDoc();
            String noSealPdfUrl = pdfUrl.get("fileUrl");
            if ("1".equals(configBusiParamDocumentInfo.getIsDeptSign()) && !YesOrNoEnum.YES.getCode().equals(isGetBlankDoc)) {
                //文书签章 1.非审批文书签章 2.审批通过文书签章
                if (("CLOSE-TRIGGER-APPROVAL-PASS".equals(saveDto.getCloseSignal()) && "1".equals(configBusiParamDocumentInfo.getIsApprove())) || !"1".equals(configBusiParamDocumentInfo.getIsApprove())) {
                    FileSealInfoQueryDto queryDto = new FileSealInfoQueryDto();
                    String uniscid = getUniscidByOrgCode(caseMainInfo.getCaseOrgCode(), caseMainInfo.getCaseDeptCode());
                    queryDto.setFileBase64(pdfUrl.get("fileBase64"));
                    String entrustClientOrgCode = getEntrustClientOrgCodeIfExists(caseId, caseMainInfo);
                    if (org.apache.commons.lang.StringUtils.isNotEmpty(entrustClientOrgCode)) {
                        SysDepartParam sysDepartParam = sysDepartParamService.getSysDepartParamByOrgCodeAndDeptCode(entrustClientOrgCode, null);
                        queryDto.setUniscid(sysDepartParam.getUnicode());
                        queryDto.setDeptCode(null);
                    } else {
                        SysDepartParam sysDepartParam = sysDepartParamService.getSysDepartParamByOrgCodeAndDeptCode(caseMainInfo.getCaseOrgCode(), caseMainInfo.getCaseDeptCode());
                        queryDto.setUniscid(sysDepartParam.getUnicode());
                        queryDto.setDeptCode(caseMainInfo.getCaseDeptCode());
                    }
                    pdfSealUrl = dealFileSeal(queryDto);
                    // pdfSealUrl=noSealPdfUrl;
                    if (log.isDebugEnabled()) {
                        log.debug("签章耗时------------------------" + (System.currentTimeMillis() - start));
                    }
                    if (StringUtils.isBlank(pdfSealUrl)) {
                        resultMap.put("success", "false");
                        resultMap.put("msg", "文书签章失败！");
                        return resultMap;
                    }
                    Map<String, Object> operateMap = operateCaseDocumentRecord(saveDto.getCaseAssistId(), saveDto.getDocumentCatalogCode(), caseMainInfo, pdfUrl.get("fileUrl"), documentNumber, paramMap, pdfSealUrl, sentDeadLine, saveDto.getIsMultipleDoc(), saveDto.getBelongDocumentId(), partyId, saveDto.getDocumentTemplateType(), saveDto.getZlbCaseDocumentRecordDto(), saveDto.getIsEditFile(), saveDto.getDocId(), templateCode);
                    num = MapUtils.getIntValue(operateMap, "num", 0);
                    documentId = MapUtils.getString(operateMap, "documentId", "");
                }
                if (!"CLOSE-TRIGGER-APPROVAL-PASS".equals(saveDto.getCloseSignal()) && "1".equals(configBusiParamDocumentInfo.getIsApprove())) {
                    //num = operateCaseDocumentRecord(saveDto.getDocumentCatalogCode(), caseMainInfo, pdfUrl.get("fileUrl"), documentNumber, paramMap, pdfSealUrl, sentDeadLine);

                    //从签字捺印过来，原先签章文件是非空的，要保留
                    CaseDocumentRecord oriRecord = null;
                    //todo 待优化调整当事人审批表需要传documentId
                    if ((DocumentKindEnum.DOC_KIND_DK1BZGZSPB.getCode().equals(documentKindCode) || DocumentKindEnum.DOC_KIND_DK1BZGZSPB.getCode().equals(documentKindCode)) && ObjectUtil.isNotEmpty(saveDto.getDocId())) {
                        oriRecord = caseDocumentRecordMapper.selectByPrimaryKey(saveDto.getDocId());
                    } else {
                        oriRecord = caseDocumentRecordService.getCaseDocumentRecord(caseId, documentCatalogCode, partyId);
                    }
                    if (!ObjectUtils.isEmpty(oriRecord) && !ObjectUtils.isEmpty(oriRecord.getDocumentUrlAfterSeal()) && !Constant.STRING_1.equals(saveDto.getIsEditFile())) {
                        pdfSealUrl = oriRecord.getDocumentUrlAfterSeal();
                    }
                    //num = operateCaseDocumentRecord(saveDto.getDocumentCatalogCode(), caseMainInfo, pdfUrl.get("fileUrl"), documentNumber, paramMap, pdfSealUrl, sentDeadLine);
                    Map<String, Object> operateMap = operateCaseDocumentRecord(saveDto.getCaseAssistId(), saveDto.getDocumentCatalogCode(), caseMainInfo, pdfUrl.get("fileUrl"), documentNumber, paramMap, pdfSealUrl, sentDeadLine, saveDto.getIsMultipleDoc(), saveDto.getBelongDocumentId(), partyId, saveDto.getDocumentTemplateType(), saveDto.getZlbCaseDocumentRecordDto(), saveDto.getIsEditFile(), saveDto.getDocId(), templateCode);
                    num = MapUtils.getIntValue(operateMap, "num", 0);
                    documentId = MapUtils.getString(operateMap, "documentId", "");
                }
                if ("CLOSE-TRIGGER-APPROVAL-PASS".equals(saveDto.getCloseSignal()) && "1".equals(configBusiParamDocumentInfo.getIsApprove())) {
                    //审批通过，关联文书签章
                    //查询关联文书
                    String relationDocumentCatalogCode = configBusiParamDocumentInfo.getRelationDocumentCatalogCode();
                    if (StringUtils.isNotBlank(relationDocumentCatalogCode)) {
                        String[] relationDocumentCatalogCodeArr = relationDocumentCatalogCode.split(",");
                        for (String relationDocumentCatalogCodeStr : relationDocumentCatalogCodeArr) {
                            log.info("caseId:{},relationDocumentCatalogCodeStr:{},partyId:{}", caseId, relationDocumentCatalogCodeArr, partyId);
                            CaseDocumentRecord caseDocumentRecord = null;
                            //如果是补正更正审批表  、调整当事人审批表
                            //todo 待优化调整当事人审批表需要传documentId
                            if ((DocumentKindEnum.DOC_KIND_DK1BZGZSPB.getCode().equals(documentKindCode) || DocumentKindEnum.DOC_KIND_DK1BZGZSPB.getCode().equals(documentKindCode)) && ObjectUtil.isNotEmpty(saveDto.getDocId())) {
                                caseDocumentRecord = caseDocumentRecordService.getRelationCaseDocumentRecord(caseId, relationDocumentCatalogCodeStr, saveDto.getDocId());
                            } else {
                                caseDocumentRecord = caseDocumentRecordService.getCaseDocumentRecord(caseId, relationDocumentCatalogCodeStr, partyId);
                            }

                            if (caseDocumentRecord != null) {
                                String documentContent = caseDocumentRecord.getDocumentContent();
                                JSONObject jsonObject = JSON.parseObject(documentContent);
                                HashMap<String, Object> jsonMap = new HashMap<>(16);
                                for (Map.Entry<String, Object> entry : jsonObject.entrySet()) {
                                    jsonMap.put(entry.getKey(), entry.getValue());
                                }
                                jsonMap.put("sealDate", DateUtils.formatDate(new Date(), "yyyy年M月d日"));
                                //审批人签名信息添加
                                HashMap<String, Object> dataMap1 = saveDto.getDataMap();
                                for (OpinionType ot : OpinionType.values()) {
                                    Object o = dataMap1.get(ot.getAuditUserIdCode());
                                    if (!ObjectUtils.isEmpty(o)) {
                                        jsonMap.put(ot.getAuditUserIdCode(), o.toString());
                                        jsonMap.put(ot.getAuditTimeCode(), DateUtils.formatDate(new Date(), "yyyy年M月d日"));
                                    }
                                }

                                //生成文号
                                ConfigBusiParamDocumentInfo relateConfigBusiParamDocumentInfo = configBusiParamDocumentInfoService.getDetailByDocumentCatalogCode(relationDocumentCatalogCodeStr);
                                //String relateDocumentNumber = genDocumentNumber(relationDocumentCatalogCodeStr, saveDto, relateConfigBusiParamDocumentInfo);
                                ConfigBusiParamDocumentInfo configInfo = configBusiParamDocumentInfoService.getDetailByDocumentCatalogCode(relationDocumentCatalogCodeStr);
                                String relatedDocumentKindCode = configInfo.getDocumentKindCode();

                                String relateDocumentNumber = "";
                                if (DocumentKindEnum.DOC_KIND_DK2BZGZTZS.getCode().equals(relatedDocumentKindCode)) {
                                    relateDocumentNumber = this.getCorrectionDocumentNumber(relationDocumentCatalogCodeStr, saveDto, configInfo);
                                } else {
                                    Map<String, Object> relateDocNumberMap = genDocumentNumber(relationDocumentCatalogCodeStr, saveDto, relateConfigBusiParamDocumentInfo);
                                    //relateDocumentNumber = relateDocNumberMap.get("documentNumber").toString();
                                    relateDocumentNumber =MapUtils.getString(relateDocNumberMap,"documentNumber","");
                                    if(relateDocNumberMap.containsKey("serialNumber")){
                                        docNumberMap = new HashMap<>();
                                        docNumberMap.put("serialNumber",relateDocNumberMap.get("serialNumber"));
                                        docNumberMap.put("serialCatalogCode",relationDocumentCatalogCodeStr);
                                        docNumberList.add(docNumberMap);
                                        if (ObjectUtil.isNotEmpty(saveDto.getExceptionCaseDocumentSerialKey())) {
                                            //审批调用, 则把文号数据存入redis, 用于审批异常文号回归
                                            String exceptionSerialStr = JSON.toJSONString(docNumberList);
                                            //将缓存加入线程上下文
                                            BusinessContextUtil.set(BusinessContextKeyEnum.DOCUMENT_NUMBER_REGRESSION_IDENTIFICATION_CODE, exceptionSerialStr);
//                                            cfRedisRepository.setExpire(saveDto.getExceptionCaseDocumentSerialKey(), exceptionSerialStr, 10 * 60);
                                        }
                                    }
                                }

                                //计算送达期限(关联文书)
                                String isSendOfRelation = relateConfigBusiParamDocumentInfo.getIsSend();
                                String isApproveOfRelation = relateConfigBusiParamDocumentInfo.getIsApprove();
                                LocalDate sentDeadLineOfRelation = null;
                                //关联文书需要送达且需要审批重新生成送达截止时间
                                if (YesOrNoEnum.YES.getCode().equals(isSendOfRelation)
                                        && YesOrNoEnum.YES.getCode().equals(isApproveOfRelation)) {
                                    Integer limitDay = relateConfigBusiParamDocumentInfo.getSendLimitDay();
                                    String limitDayType = relateConfigBusiParamDocumentInfo.getSendLimitType();
                                    sentDeadLineOfRelation = caseDocumentRecordService.calculateSentDeadLine(caseId, relationDocumentCatalogCodeStr, limitDay, limitDayType, false);
                                    if (ObjectUtils.isEmpty(sentDeadLineOfRelation)) {
                                        throw new BusinessException("未获取到文书送达期限-caseId:" + caseId + ",documentCatalogCode:" + relationDocumentCatalogCodeStr);
                                    }
                                }

                                //处罚决定书文号更新至案件详情表
                                if (!ObjectUtils.isEmpty(relateDocumentNumber) && (Constant.STRING_KIND_CODE_CFJDS.equals(relatedDocumentKindCode) || Constant.STRING_KIND_CODE_BYCFJDS.equals(relatedDocumentKindCode))) {
                                    //判断是否多当事人分别处罚
                                    if (caseMainInfoService.checkCaseIsPartiesPartPunish(caseId, null)) {
                                        CaseMainDetailAuxiliaryInfo caseMainDetailAuxiliaryInfo = new CaseMainDetailAuxiliaryInfo();
                                        caseMainDetailAuxiliaryInfo.setCaseId(caseId);
                                        caseMainDetailAuxiliaryInfo.setPartyId(partyId);
                                        caseMainDetailAuxiliaryInfo.setPunishDocumentNumber(relateDocumentNumber);
                                        caseMainDetailAuxiliaryInfoService.updateSpecialParam(caseMainDetailAuxiliaryInfo);
                                    } else {
                                        CaseMainDetailInfo caseMainDetailInfo = new CaseMainDetailInfo();
                                        caseMainDetailInfo.setCaseId(caseId);
                                        caseMainDetailInfo.setPunishDocumentNumber(relateDocumentNumber);
                                        caseMainDetailInfoMapper.updateByPrimaryKeySelective(caseMainDetailInfo);
                                        try {
                                            //单当事人单案由 更新补充表数据
                                            CaseMainDetailAuxiliaryInfo caseMainDetailAuxiliaryInfo = new CaseMainDetailAuxiliaryInfo();
                                            caseMainDetailAuxiliaryInfo.setCaseId(caseId);
                                            caseMainDetailAuxiliaryInfo.setPunishDocumentNumber(relateDocumentNumber);
                                            caseMainDetailAuxiliaryInfoService.editSpecialParamSingle(caseMainDetailAuxiliaryInfo);
                                        } catch (Exception e) {
                                            e.printStackTrace();
                                        }

                                    }
                                }
                                jsonMap.put("documentNumber", relateDocumentNumber);
                                String relateTemplateCode = getTemplateCodeByDocumentCatalogCode(relationDocumentCatalogCodeStr, caseId, jsonMap, saveDto.getPartyId());
                                FillAndConvertToPdfRequest relatePdfRequest = new FillAndConvertToPdfRequest();
                                //行政行为二维码条形码添加
                                if (Constant.STRING_1.equals(relateConfigBusiParamDocumentInfo.getIsWatermark()) && Constant.STRING_TRUE.equals(isEnable)) {
                                    //if (Constant.STRING_1.equals(relateConfigBusiParamDocumentInfo.getIsWatermark())&&Constant.STRING_TRUE.equals(isEnable)&&TerritoryCodeEnum.ZHZF.getCode().equals(caseMainInfoVo.getCaseTerritoryCode())) {
                                    boolean isWatermak = true;
                                    //立案审批表最后一次审批添加水印
                                    if (DocumentKindEnum.DOC_KIND_LASPB.getCode().equals(documentKindCode) && !"CLOSE-TRIGGER-APPROVAL-PASS".equals(saveDto.getCloseSignal())) {
                                        isWatermak = false;
                                    }
                                    if (isWatermak) {
                                        HashMap<String, Object> dataMap = saveDto.getDataMap();
                                        jsonMap.put("qrCodeUrl", caseMainInfoVo.getCaseQrCodeUrl());
                                        jsonMap.put("barCodeUrl", caseMainInfoVo.getCaseBarCodeUrl());
                                        relatePdfRequest.setIsWatermark(Constant.STRING_1);
                                        relatePdfRequest.setWatermarkContent(caseMainInfoVo.getCaseActsCode());
                                    }
                                }
                                relatePdfRequest.setTemplateCode(relateTemplateCode);
                                relatePdfRequest.setParamMap(jsonMap);
                                Map<String, String> relatePdfUrl = getConvertedPdfUrl(relatePdfRequest);
                                System.out.println("关联文书生成耗时------------------------" + (System.currentTimeMillis() - start));
                                // String fileBase64=;
                                String uniscid = getUniscidByOrgCode(caseMainInfo.getCaseOrgCode(), caseMainInfo.getCaseDeptCode());
                                FileSealInfoQueryDto queryDto = new FileSealInfoQueryDto();
                                queryDto.setFileBase64(relatePdfUrl.get("fileBase64"));
                                queryDto.setUniscid(uniscid);
                                queryDto.setDeptCode(caseMainInfo.getCaseDeptCode());
                                String relatePdfSealUrl = dealFileSeal(queryDto);
                                //String relatePdfSealUrl =relatePdfUrl.get("fileUrl");
                                if (log.isDebugEnabled()) {
                                    log.debug("关联文书签章耗时------------------------" + (System.currentTimeMillis() - start));
                                }
                                //operateCaseDocumentRecord(relationDocumentCatalogCodeStr, caseMainInfo, relatePdfUrl.get("fileUrl"), relateDocumentNumber, paramMap, relatePdfSealUrl, sentDeadLine);
                                operateCaseDocumentRecord(saveDto.getCaseAssistId(), relationDocumentCatalogCodeStr, caseMainInfo, relatePdfUrl.get("fileUrl"), relateDocumentNumber, jsonMap, relatePdfSealUrl, sentDeadLineOfRelation, saveDto.getIsMultipleDoc(), saveDto.getBelongDocumentId(), partyId, saveDto.getDocumentTemplateType(), saveDto.getZlbCaseDocumentRecordDto(), "", caseDocumentRecord.getId(), templateCode);
                                if (StringUtils.isBlank(pdfSealUrl)) {
                                    resultMap.put("success", "false");
                                    resultMap.put("msg", "文书签章失败！");
                                    return resultMap;
                                }
                            }
                        }
                    }
                }
            } else {
                //num = operateCaseDocumentRecord(saveDto.getDocumentCatalogCode(), caseMainInfo, pdfUrl.get("fileUrl"), documentNumber, paramMap, pdfSealUrl, sentDeadLine);
                Map<String, Object> operateMap = operateCaseDocumentRecord(saveDto.getCaseAssistId(), saveDto.getDocumentCatalogCode(), caseMainInfo, pdfUrl.get("fileUrl"), documentNumber, paramMap, pdfSealUrl, sentDeadLine, saveDto.getIsMultipleDoc(), saveDto.getBelongDocumentId(), partyId, saveDto.getDocumentTemplateType(), saveDto.getZlbCaseDocumentRecordDto(), saveDto.getIsEditFile(), saveDto.getDocId(), templateCode);
                num = MapUtils.getIntValue(operateMap, "num", 0);
                documentId = MapUtils.getString(operateMap, "documentId", "");
            }
            if (("CLOSE-TRIGGER-APPROVAL-PASS".equals(saveDto.getCloseSignal()) && "1".equals(configBusiParamDocumentInfo.getIsApprove())) || !"1".equals(configBusiParamDocumentInfo.getIsApprove())) {
                //处罚决定撤销时相关流程更新
                CasePunishDecisionRevokeRecordVo vo = casePunishDecisionRevokeRecordService.getCasePunishDecisionRevokeRecordBasicInfo(caseId);
                if (!ObjectUtils.isEmpty(vo)) {
                    String revokeReasonCode = vo.getRevokeReasonCode();
                    if (PunishDecisionRevokeReasonEnum.FYSSHCX.getCode().equals(revokeReasonCode)) {
                        //没有行政处罚撤销决定书
                        if (Constant.STRING_KIND_CODE_XZCFCXSPB.equals(documentKindCode)) {
                            casePunishDecisionRevokeRecordService.dealAfterPunishRevoke(caseId, vo.getDealAfterRevokeTypeCode());
                        }
                    }
                }
                if (DocumentKindEnum.DOC_KIND_DK1TZDSRNBSPB.getCode().equals(documentKindCode)) {
                    caseInfoAdjustRecordService.updateAdjustPartyRecordAfterApproval(documentId);
                }

                //公示变更
                if (CasePublicityModifyEnum.isLegalEnumCodeByKindCode(documentKindCode)) {
                    casePublicityModifyRecordService.dealPublicityModifyAfterFinishApproval(caseId, documentKindCode, documentId);
                }
            }
            //操作文书记录表 判断文书记录是否存在，存在则添加历史表，然后更新数据
            if (num < 1) {
                resultMap.put("success", "false");
                resultMap.put("msg", "保存失败！");
                return resultMap;
            }
            if (CaseStatusEnum.PUNISH_NO_REGISTER.getCode().equals(caseMainInfoVo.getCaseStatus()) && ApiVisitDataSourceEnum.PUNISH_AY.getCode().equals(caseMainInfoVo.getDataSource())) {
                resultMap.put("success", "true");
                resultMap.put("msg", "生成成功！");
                return resultMap;
            }
            //送达回证特殊处理
            String receiptDocUrl = pdfSealUrl;
            if (YesOrNoEnum.YES.getCode().equals(isGetBlankDoc)) {
                //空白送达回证无需签章
                receiptDocUrl = noSealPdfUrl;
            } else {
                receiptDocUrl = pdfSealUrl;
            }
            updateDocumentRecordInfoAfterSentReceiptPrint(documentCatalogCode, pdfUrl, receiptDocUrl, caseId, isGetBlankDoc, partyId);
            System.out.println("送达回证特殊处理耗时------------------------" + (System.currentTimeMillis() - start));
            //非诉执行立案申请
            nonLitigationExecute(saveDto);
            //案件状态变更操作
            updateCaseStatusChange(saveDto, documentId, configBusiParamDocumentInfo);
            //若需要更新则根据配置更新相关数据
            if (!YesOrNoEnum.NO.getCode().equals(saveDto.getIsUpdateRelationTable())
                    || DocumentKindEnum.DOC_KIND_SDDZQRS.getCode().equals(documentKindCode)) {
                if (DocumentKindEnum.DOC_KIND_SDDZQRS.getCode().equals(documentKindCode)) {
                    log.info("送达方式及地址确认书根据配置更新相关数据-- DocumentCatalogCode:" + saveDto.getDocumentCatalogCode() + "caseId:" + caseId);
                }
                operateBusiTableByDocumentCatalogCode(saveDto);
            }
            String closeSignal = saveDto.getCloseSignal();
            if (StringUtils.isBlank(closeSignal)) {
                closeSignal = "CLOSE-TRIGGER-DOCCREATE";
            }
            resultMap.put("closeSignal", closeSignal);
            //简易程序案件流程无需滚动,不设置workId
            //非简易程序并且不为修改文书时设置workId
            if (!CaseTypeEnum.SIMPLE_PROCEDURE.getCode().equals(caseMainInfo.getCaseType()) && !Constant.STRING_1.equals(saveDto.getIsEditFile())) {
                resultMap.put("workId", caseId);
            }
            resultMap.put("documentId", documentId);
            resultMap.put("documentCatalogCode", documentCatalogCode);
            if (StringUtils.isNotBlank(saveDto.getCaseAssistId())) {
                resultMap.put("workAssistId", saveDto.getCaseAssistId());
            }
            // 为了验收需求 责令改正发送大综合消息
            if (Constant.STRING_KIND_CODE_ZLGZTZS.equals(documentKindCode)) {
                Example example3 = new Example(CasePartiesRecord.class);
                Example.Criteria criteria = example3.createCriteria();
                criteria.andEqualTo("caseId", caseId).andEqualTo("status", Constant.STRING_1).andEqualTo("partyType", Constant.STRING_2);
                if (StringUtils.isNotBlank(partyId)) {
                    criteria.andEqualTo("partyId", partyId);
                }
                List<CasePartiesRecord> casePartiesRecords = casePartiesRecordMapper.selectByExample(example3);
                if (org.apache.commons.lang3.ObjectUtils.isNotEmpty(casePartiesRecords) && casePartiesRecords.size() > 0) {
                    PunishMsgParams punishMsgParams = new PunishMsgParams();
                    punishMsgParams.setContent("您企业收到一份整改通知书");
                    punishMsgParams.setTitle("责令整改通知书");
                    punishMsgParams.setSourceUrl(pdfSealUrl);
                    punishMsgParams.setType(Constant.STRING_4);
                    punishMsgParams.setUniCode(casePartiesRecords.get(0).getPartyIdentityCode());
                    punishMsgParams.setDeptName(caseMainInfo.getCaseOrgName());
                    punishMsgParams.setSendTime(new Date());
                    caseApprovalWaitRecordService.comprehensiveMsg(punishMsgParams);
                }
            }
            // 证据库案件信息同步对接
            try {
                String la = "LASPB";
                if (saveDto.getDocumentCatalogCode().contains(la) && StringUtils.isNotBlank(documentNumber) && !Constant.STRING_1.equals(saveDto.getIsEditFile())) {
                    //调用行政行为码赋码接口 同时生成二维码 与 条形码
                    //caseActsCodeInfoService.saveCaseActsCodeInfo(caseMainInfoVo);
                    // 换为证据库新API 测试正式调用
                    if (SpringContextUtil.checkIsPrdProfile() || SpringContextUtil.checkIsDevProfile()) {
                        evidenceInventoryService.saveEvent(caseId, documentNumber);
                    }
                }
            } catch (Exception e) {
                log.info("证据库立案对接失败:{}", e.getMessage());
            }
        }catch (Exception e){
            //该方法一旦发生异常，且生成了文号的情况下，则触发文号回归文号池的策略（当前文号池先以表进行存储）
            if(docNumberList.size()>0){
                LogsCaseDocumentSerialRecord logsCaseDocumentSerialRecord = new LogsCaseDocumentSerialRecord();
                logsCaseDocumentSerialRecord.setBusiId(caseId);
                for (Map<String, Object> docNumberExcepMap : docNumberList){
                    //序列的文书目录编码处理
                    String serialCatalogCode1 = docNumberExcepMap.get("serialCatalogCode").toString();
                    ConfigBusiParamDocumentInfo configBusiParamDocumentInfo = configBusiParamDocumentInfoService.getDetailByDocumentCatalogCode(serialCatalogCode1);
                    if ("4".equals(configBusiParamDocumentInfo.getDocumentNumberSerialType())) {
                        //4-与某文书使用相同序列
                        serialCatalogCode1 = configBusiParamDocumentInfo.getDocumentNumberMatchCatalogCode();
                    }
                    logsCaseDocumentSerialRecord.setDocumentCatalogCode(serialCatalogCode1);
                    logsCaseDocumentSerialRecord.setSerial((Long)docNumberExcepMap.get("serialNumber"));
                    logsCaseDocumentSerialRecordService.modLogsCaseDocumentSerialRecordException(logsCaseDocumentSerialRecord);
                }
            }
            if(e instanceof BusinessException){
                throw new BusinessException(e.getMessage());
            }else{
                throw e;
            }
        }
        return resultMap;
    }

    /**
     * 描述：保存补正/更正文书信息
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public CorrectionDocSaveVo saveCorrectionDocInfo(CorrectionDocSaveDto saveDto) {
        //参数判断
        this.checkSaveCorrectionDocInfoParam(saveDto);
        CorrectionDocSaveVo correctionDocSaveVo = new CorrectionDocSaveVo();
        CaseMainInfo caseMainInfo = caseMainInfoMapper.selectByPrimaryKey(saveDto.getCaseId());
        //如果是已结案，则不能保存
        //V11.3后更改为结案可以操作
//        if(CaseStatusEnum.END_CASE.getCode().equals(caseMainInfo.getCaseStatus())){
//            throw new BusinessException("案件已结案，无法操作");
//        }
        //分别处罚时，partyID不能为空
        if (HandleTypeEnum.PART_PUNISH.getCode().equals(caseMainInfo.getHandleType())) {
            if (StrUtil.isEmpty(saveDto.getCorrectionApproveDoc().getPartyId()) || StrUtil.isEmpty(saveDto.getCorrectionApproveDoc().getPartyId())) {
                throw new BusinessException("分别处罚时，partyID不能为空");
            }
        }
        UserDTO userDTO = UserUtil.getUserInfo();

        //查询关联文书记录
        CaseDocumentRecord relationRecordInfo = caseDocumentRecordMapper.selectByPrimaryKey(saveDto.getRelationDocumentRecordId());
        if (ObjectUtil.isEmpty(relationRecordInfo)) {
            throw new BusinessException("查询文书记录失败");
        }

        //获取partyID
        if (StrUtil.isEmpty(saveDto.getCorrectionApproveDoc().getPartyId()) || StrUtil.isEmpty(saveDto.getCorrectionApproveDoc().getPartyId())) {
            Example partyExample = new Example(CasePartiesRecord.class);
            partyExample.createCriteria().andEqualTo("caseId", caseMainInfo.getId()).andEqualTo("status", "1");
            partyExample.orderBy("partyType").desc();
            List<CasePartiesRecord> partiesRecords = casePartiesRecordMapper.selectByExample(partyExample);
            List<String> partyIdList = CollUtil.newArrayList();
            partiesRecords.forEach(u -> partyIdList.add(u.getPartyId()));
            String partyIds = CollUtil.join(partyIdList, Constant.STRING_COMMA);
            saveDto.getCorrectionApproveDoc().setPartyId(partyIds);
            saveDto.getCorrectionDoc().setPartyId(partyIds);
        }

        //保存或者更新审批表
        saveDto.getCorrectionApproveDoc().setRelationApprovalDocumentId(null);
        this.saveCorrectionDocInfo(saveDto.getCorrectionApproveDoc(), caseMainInfo, relationRecordInfo, userDTO);
        //保存或者更新通知书
        //拿到审批表的文书记录ID
        saveDto.getCorrectionDoc().setRelationApprovalDocumentId(saveDto.getCorrectionApproveDoc().getDocumentRecordId());
        this.saveCorrectionDocInfo(saveDto.getCorrectionDoc(), caseMainInfo, relationRecordInfo, userDTO);
        correctionDocSaveVo.setRelationApprovalDocumentId(saveDto.getCorrectionApproveDoc().getDocumentRecordId());
        correctionDocSaveVo.setRelationDocumentId(saveDto.getCorrectionDoc().getDocumentRecordId());
        return correctionDocSaveVo;
    }

    /**
     * 保存补正/更正送达回证
     *
     * @param saveDetailDto
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveCorrectionConfirmSend(CorrectionDocSaveDetailDto saveDetailDto) {
        CaseMainInfo caseMainInfo = caseMainInfoMapper.selectByPrimaryKey(saveDetailDto.getCaseId());
        //如果是已结案，则不能保存
        ////V1.1.3结案时可以操作
//        if(CaseStatusEnum.END_CASE.getCode().equals(caseMainInfo.getCaseStatus())){
//            throw new BusinessException("案件已结案，无法操作");
//        }
        UserDTO userDTO = UserUtil.getUserInfo();

        //查询关联文书记录
        CaseDocumentRecord relationRecordInfo = caseDocumentRecordMapper.selectByPrimaryKey(saveDetailDto.getRelationDocumentRecordId());
        if (ObjectUtil.isEmpty(relationRecordInfo)) {
            throw new BusinessException("查询文书记录失败");
        }

        //获取partyID
        if (StrUtil.isEmpty(saveDetailDto.getPartyId())) {
            Example partyExample = new Example(CasePartiesRecord.class);
            partyExample.createCriteria().andEqualTo("caseId", caseMainInfo.getId()).andEqualTo("status", "1");
            partyExample.orderBy("partyType").desc();
            List<CasePartiesRecord> partiesRecords = casePartiesRecordMapper.selectByExample(partyExample);
            List<String> partyIdList = CollUtil.newArrayList();
            partiesRecords.forEach(u -> partyIdList.add(u.getPartyId()));
            String partyIds = CollUtil.join(partyIdList, Constant.STRING_COMMA);
            saveDetailDto.setPartyId(partyIds);
        }
        this.saveCorrectionDocInfo(saveDetailDto, caseMainInfo, relationRecordInfo, userDTO);
    }

    /**
     * 保存补正/更正文书
     *
     * @param dto
     * @param caseMainInfo
     * @param relationRecordInfo
     * @param userDTO
     */
    private void saveCorrectionDocInfo(CorrectionDocSaveDetailDto dto, CaseMainInfo caseMainInfo, CaseDocumentRecord relationRecordInfo, UserDTO userDTO) {
        //查询文书配置信息
        ConfigBusiParamDocumentInfo configDocumentInfo = configBusiParamDocumentInfoService.getConfigBusiParamDocumentInfoByBusiParamIdAndCode(caseMainInfo.getBusiParamId(), dto.getDocumentCatalogCode());
        //如果是修改，则直接拿之前的模板
        String templateCode = this.getDocumentTemplateCode(dto, caseMainInfo, configDocumentInfo);
        //文书参数
        Map<String, Object> paramMap = dto.getDataMap();

        FillAndConvertToPdfRequest pdfRequest = new FillAndConvertToPdfRequest();
        pdfRequest.setTemplateCode(templateCode);
        pdfRequest.setParamMap(paramMap);
        //判断文书模板类型是否为窄幅
        if (DocumentTemplateTypeEnum.NARROW_TEMPLATE.getCode().equals(dto.getDocumentTemplateType())) {
            pdfRequest.setTemplateType(DocumentTemplateKindEnum.NARROW_TEMPLATE.getCode());
        }
        Map<String, String> pdfUrl = getConvertedPdfUrl(pdfRequest);
        String noSealPdfUrl = pdfUrl.get("fileUrl");

        //计算文书送达期限
        Integer limitDay = configDocumentInfo.getSendLimitDay();
        String limitDayType = configDocumentInfo.getSendLimitType();
        LocalDate sentDeadLine = caseDocumentRecordService.calculateSentDeadLine(caseMainInfo.getId(), dto.getDocumentCatalogCode(), limitDay, limitDayType, false);

        CaseDocumentRecord recordInfo = null;
        //查询是否有暂存的草稿，如果有的话，则更新草稿
        if (StrUtil.isEmpty(dto.getDocumentRecordId())) {
            Example example = new Example(CaseDocumentRecord.class);
            example.createCriteria().andEqualTo("documentCatalogCode", dto.getDocumentCatalogCode())
                    .andEqualTo("documentRecordStatus", "2")
                    .andEqualTo("relationDocumentId", relationRecordInfo.getId());
            List<CaseDocumentRecord> recordInfoList = caseDocumentRecordMapper.selectByExample(example);
            if (ObjectUtil.isNotEmpty(recordInfoList)) {
                recordInfo = recordInfoList.get(Constant.INTEGER_0);
            }
        } else {
            recordInfo = caseDocumentRecordMapper.selectByPrimaryKey(dto.getDocumentRecordId());
        }

        String sealUrl = null;
        //如果是补正/更正的送达回证，则直接签章
        if (DocumentKindEnum.DOC_KIND_SDHZ.getCode().equals(configDocumentInfo.getDocumentKindCode())) {
            sealUrl = this.getPdfSealUrl(caseMainInfo, pdfUrl);
        }

        //更新
        if (ObjectUtil.isNotEmpty(recordInfo)) {
            //添加历史
            CaseDocumentRecordHis caseDocumentRecordHis = new CaseDocumentRecordHis();
            BeanUtils.copyProperties(recordInfo, caseDocumentRecordHis);
            //增加创建时间设置
            try {
                Date createTime = Date.from(recordInfo.getDocumentCreateTime().atZone(ZoneId.systemDefault()).toInstant());
                caseDocumentRecordHis.setDocumentCreateTime(createTime);
            } catch (Exception e) {
            }
            caseDocumentRecordHis.setId(StringUtils.uuid());
            caseDocumentRecordHis.setRecordId(recordInfo.getId());
            caseDocumentRecordHis.setOp("update");
            caseDocumentRecordHis.setHisCreateTime(new Date());
            caseDocumentRecordHisMapper.insert(caseDocumentRecordHis);

            //更新文书记录表
            recordInfo.setDocumentUrl(noSealPdfUrl);
            recordInfo.setSentDeadline(sentDeadLine);
            recordInfo.setDocumentContent(JSONObject.toJSON(paramMap).toString());
            recordInfo.setPartyId(dto.getPartyId());//设置当事人id`
            if (DocumentRecordStatusEnum.DRAFT.getCode().equals(recordInfo.getDocumentRecordStatus())) {
                //生成默认待提交状态
                if ("1".equals(configDocumentInfo.getIsApprove())) {
                    recordInfo.setDocumentApprovalStatus(DocumentStatusEnum.WAIT_TO_SUBMIT.getCode());
                    recordInfo.setDocumentAuditStatus("notSubmit");
                }
                if ("1".equals(configDocumentInfo.getIsSend())) {
                    recordInfo.setDocumentSentStatus(DocumentStatusEnum.WAIT_TO_SEND.getCode());
                }
                if (BusinessContextUtil.documentNeedConfirm(configDocumentInfo)) {
                    recordInfo.setDocumentSignstampedStatus(DocumentStatusEnum.WAIT_TO_CONFIRM.getCode());
                }
                //设置和关联文书一样的阶段
                recordInfo.setCaseStageName(relationRecordInfo.getCaseStageName());
                recordInfo.setCaseStageCode(relationRecordInfo.getCaseStageCode());
                recordInfo.setCaseLinkCode(relationRecordInfo.getCaseLinkCode());
                recordInfo.setCaseLinkName(relationRecordInfo.getCaseLinkName());
            }
            if (!ObjectUtils.isEmpty(dto.getDocumentTemplateType())) { //设置模板类型
                recordInfo.setDocumentTemplateType(dto.getDocumentTemplateType());
            }
            if (StrUtil.isNotEmpty(dto.getRelationApprovalDocumentId())) {
                recordInfo.setRelationApprovalDocumentId(dto.getRelationApprovalDocumentId());
            }
            recordInfo.setDocumentRecordStatus(DocumentRecordStatusEnum.NORMAL.getCode());//设置文书为正常状态
            recordInfo.setCreateUserName(userDTO.getRealName());
            recordInfo.setCreateUserId(userDTO.getUserId().toString());
            recordInfo.setRelationDocumentId(relationRecordInfo.getId());
            recordInfo.setDocumentUrlAfterSeal(sealUrl);
            caseDocumentRecordMapper.updateByPrimaryKeySelective(recordInfo);
            dto.setDocumentRecordId(recordInfo.getId());
        } else {
            CaseDocumentRecord caseDocumentRecord = new CaseDocumentRecord();
            caseDocumentRecord.setCaseId(caseMainInfo.getId());
            caseDocumentRecord.setId(StringUtils.uuid());
            //设置和关联文书一样的阶段
            caseDocumentRecord.setCaseStageName(relationRecordInfo.getCaseStageName());
            caseDocumentRecord.setCaseStageCode(relationRecordInfo.getCaseStageCode());
            caseDocumentRecord.setCaseLinkCode(relationRecordInfo.getCaseLinkCode());
            caseDocumentRecord.setCaseLinkName(relationRecordInfo.getCaseLinkName());
            caseDocumentRecord.setDocumentCatalogCode(configDocumentInfo.getDocumentCatalogCode());
            caseDocumentRecord.setDocumentUrl(noSealPdfUrl);
            caseDocumentRecord.setSentDeadline(sentDeadLine);
            caseDocumentRecord.setDocumentCreateTime(LocalDateTime.now());
            caseDocumentRecord.setDocumentContent(JSONObject.toJSON(paramMap).toString());
            //生成默认待提交状态
            if ("1".equals(configDocumentInfo.getIsApprove())) {
                caseDocumentRecord.setDocumentApprovalStatus(DocumentStatusEnum.WAIT_TO_SUBMIT.getCode());
                caseDocumentRecord.setDocumentAuditStatus("notSubmit");
            }
            if ("1".equals(configDocumentInfo.getIsSend())) {
                caseDocumentRecord.setDocumentSentStatus(DocumentStatusEnum.WAIT_TO_SEND.getCode());
            }
            if (BusinessContextUtil.documentNeedConfirm(configDocumentInfo)) {
                caseDocumentRecord.setDocumentSignstampedStatus(DocumentStatusEnum.WAIT_TO_CONFIRM.getCode());
            }
            caseDocumentRecord.setCreateUserName(userDTO.getRealName());
            caseDocumentRecord.setCreateUserId(userDTO.getUserId().toString());
            //caseDocumentRecord.setDocumentUrlAfterSeal(noSealPdfUrl);
            caseDocumentRecord.setDocumentRecordStatus(DocumentRecordStatusEnum.NORMAL.getCode());//设置文书为正常状态
            //设置当事人id
            caseDocumentRecord.setPartyId(dto.getPartyId());
            if (!ObjectUtils.isEmpty(dto.getDocumentTemplateType())) { //设置模板类型
                caseDocumentRecord.setDocumentTemplateType(dto.getDocumentTemplateType());
            }
            if (StrUtil.isNotEmpty(dto.getRelationApprovalDocumentId())) {
                caseDocumentRecord.setRelationApprovalDocumentId(dto.getRelationApprovalDocumentId());
            }
            caseDocumentRecord.setDocumentTemplateCode(templateCode);
            caseDocumentRecord.setRelationDocumentId(relationRecordInfo.getId());
            caseDocumentRecord.setDocumentUrlAfterSeal(sealUrl);
            caseDocumentRecordMapper.insert(caseDocumentRecord);
            dto.setDocumentRecordId(caseDocumentRecord.getId());
        }
    }

    /**
     * 获取已签章的文书
     *
     * @param caseMainInfo
     * @param pdfUrl
     * @return
     */
    private String getPdfSealUrl(CaseMainInfo caseMainInfo, Map<String, String> pdfUrl) {
        FileSealInfoQueryDto queryDto = new FileSealInfoQueryDto();
        String uniscid = getUniscidByOrgCode(caseMainInfo.getCaseOrgCode(), caseMainInfo.getCaseDeptCode());
        queryDto.setFileBase64(pdfUrl.get("fileBase64"));
        queryDto.setUniscid(uniscid);
        queryDto.setDeptCode(caseMainInfo.getCaseDeptCode());
        return dealFileSeal(queryDto);
    }

    /**
     * 校验参数
     *
     * @param saveDto
     */
    private void checkSaveCorrectionDocInfoParam(CorrectionDocSaveDto saveDto) {
        CorrectionDocSaveDetailDto correctionApproveDoc = saveDto.getCorrectionApproveDoc();
        CorrectionDocSaveDetailDto correctionDoc = saveDto.getCorrectionDoc();
        if (StrUtil.isEmpty(saveDto.getCaseId())) {
            throw new BusinessException("案件主键ID不能为空");
        }
        if (StrUtil.isEmpty(saveDto.getRelationDocumentRecordId())) {
            throw new BusinessException("补正/更正关联文书主键ID不能为空");
        }
        if (StrUtil.isEmpty(correctionApproveDoc.getDocumentCatalogCode()) || StrUtil.isEmpty(correctionDoc.getDocumentCatalogCode())) {
            throw new BusinessException("文书目录编码不能为空");
        }
        if (ObjectUtil.isEmpty(correctionApproveDoc.getDataMap()) || ObjectUtil.isEmpty(correctionDoc.getDataMap())) {
            throw new BusinessException("文书内容不能为空");
        }
        //判断是否存在未送达的文书
//        Example example = new Example(CaseDocumentRecord.class);
//        example.createCriteria().andEqualTo("caseId", saveDto.getCaseId())
//                .andEqualTo("relationDocumentId", saveDto.getRelationDocumentRecordId())
//                .andCondition("document_sent_status != 'SEND_1' and document_record_status = '1'");
//        int count = caseDocumentRecordMapper.selectCountByExample(example);
//        if(count > Constant.INTEGER_0){
//            throw new BusinessException("当前文书存在未送达的补正/更正的文书，请处理后再试！");
//        }
    }

    /**
     * 获取文书模板
     *
     * @param dto
     * @param caseMainInfo
     * @param configDocumentInfo
     * @return
     */
    private String getDocumentTemplateCode(CorrectionDocSaveDetailDto dto, CaseMainInfo caseMainInfo, ConfigBusiParamDocumentInfo configDocumentInfo) {
        String templateCode = "";
        if (StrUtil.isNotEmpty(dto.getDocumentRecordId())) {
            CaseDocumentRecord recordInfo = caseDocumentRecordMapper.selectByPrimaryKey(dto.getDocumentRecordId());
            if (ObjectUtil.isEmpty(recordInfo)) {
                throw new BusinessException("获取文书记录失败");
            }
            return recordInfo.getDocumentTemplateCode();
        }

        //如果是多当事人
        if (PartiesReasonTypeEnum.MULTIPLE_PARTIES.getCode().equals(caseMainInfo.getCasePartiesReasonType())) {
            //分别处罚
            if (HandleTypeEnum.PART_PUNISH.getCode().equals(caseMainInfo.getHandleType())) {
                //根据当事人类型去判断
                if (StrUtil.isEmpty(dto.getPartyId())) {
                    throw new BusinessException("多当事人分别处罚时，当事人ID不能为空");
                }
                CasePartiesRecordVo partiesRecordVo = casePartiesRecordService.getCasePartiesInfoByPartyId(caseMainInfo.getId(), dto.getPartyId());
                if (PartyTypeEnum.PERSON.getCode().equals(partiesRecordVo.getPartyType())) {
                    templateCode = configDocumentInfo.getTemplatePersonCode();
                } else {
                    templateCode = configDocumentInfo.getTemplateLegalCode();
                }
            } else {//合并处罚，使用个人模板
                templateCode = configDocumentInfo.getTemplatePersonCode();
            }
        } else {
            Example example = new Example(CasePartiesRecord.class);
            example.createCriteria().andEqualTo("caseId", caseMainInfo.getId()).andEqualTo("status", Constant.STRING_1);
            List<CasePartiesRecord> partiesRecords = casePartiesRecordMapper.selectByExample(example);
            if (ObjectUtil.isEmpty(partiesRecords)) {
                throw new BusinessException("根据caseID获取当事人失败");
            }
            CasePartiesRecord casePartiesRecord = partiesRecords.get(Constant.INTEGER_0);
            if (PartyTypeEnum.PERSON.getCode().equals(casePartiesRecord.getPartyType())) {
                templateCode = configDocumentInfo.getTemplatePersonCode();
            } else {
                templateCode = configDocumentInfo.getTemplateLegalCode();
            }
        }
        return templateCode;
    }

    /**
     * 根据案件部门编码获取统一信用代码
     *
     * @param caseOrgCode
     * @return {@link String}
     * @author liyafeng
     * @date 2022/11/17
     */
    private String getUniscidByOrgCode(String caseOrgCode, String caseDeptCode) {
        String uniscid = "";
        /*Example example=new Example(SysDepartParam.class);
        example.createCriteria().andEqualTo("orgCode",caseOrgCode);
        List<SysDepartParam> sysDepartParams=sysDepartParamMapper.selectByExample(example);
        if(!ObjectUtils.isEmpty(sysDepartParams)){
            uniscid=sysDepartParams.get(0).getUnicode();
        }*/
        SysDepartParam sysDepartParam = sysDepartParamService.getSysDepartParamByOrgCodeAndDeptCode(caseOrgCode, caseDeptCode);
        if (null != sysDepartParam) {
            uniscid = sysDepartParam.getUnicode();
        }
        return uniscid;
    }


    /**
     * 根据条件生成文号
     *
     * @param saveDto
     * @param configBusiParamDocumentInfo
     * @return {@link String}
     * @author liyafeng
     * @date 2022/3/12
     */
    private Map<String, Object> genDocumentNumber(String documentCatalogCode, StageDocCommonOperateSaveDto saveDto, ConfigBusiParamDocumentInfo configBusiParamDocumentInfo) {
        Map<String, Object> resultMap = new HashMap<>();
        String documentNumber = "";
        //判断文号是否已生成
        CaseDocumentRecord caseDocumentRecord = null;
        if (StringUtils.isBlank(saveDto.getIsMultipleDoc()) || Constant.STRING_0.equals(saveDto.getIsMultipleDoc())) {
            caseDocumentRecord = caseDocumentRecordService.getCaseDocumentRecord(saveDto.getCaseId(), documentCatalogCode, saveDto.getPartyId());
        }
        if (StringUtils.isNotBlank(saveDto.getIsMultipleDoc()) && Constant.STRING_1.equals(saveDto.getIsMultipleDoc()) && StringUtils.isNotBlank(saveDto.getBelongDocumentId())) {
            caseDocumentRecord = caseDocumentRecordMapper.selectByPrimaryKey(saveDto.getBelongDocumentId());
        }
        if (null != caseDocumentRecord && StringUtils.isNotBlank(caseDocumentRecord.getDocumentNumber())) {
            documentNumber = caseDocumentRecord.getDocumentNumber();
            resultMap.put("documentNumber",documentNumber);
            return resultMap;
        }
        String docNoGene = configBusiParamDocumentInfo.getDocNoGene();
        String isApprove = configBusiParamDocumentInfo.getIsApprove();
        if ("1".equals(docNoGene)) {
            //审批前
            resultMap = getDocumentNumber(saveDto.getCaseId(), documentCatalogCode, saveDto.getPartyId());
        } else if ("CLOSE-TRIGGER-APPROVAL-PASS".equals(saveDto.getCloseSignal()) && "1".equals(configBusiParamDocumentInfo.getIsApprove())) {
            //审批完成后
            resultMap = getDocumentNumber(saveDto.getCaseId(), documentCatalogCode, saveDto.getPartyId());
        } else if (Constant.STRING_1.equals(configBusiParamDocumentInfo.getIsGenDocnum())) {
            // 需要生成文号并且不需要审批
            if (!"1".equals(isApprove)) {
                resultMap = getDocumentNumber(saveDto.getCaseId(), documentCatalogCode, saveDto.getPartyId());
            }
        }
        return resultMap;
    }

    /**
     * 获取补正/更正文书的文号
     *
     * @param documentCatalogCode         补正/更正通知书的文书目录编码
     * @param saveDto
     * @param configBusiParamDocumentInfo
     * @return
     */
    private String getCorrectionDocumentNumber(String documentCatalogCode, StageDocCommonOperateSaveDto saveDto, ConfigBusiParamDocumentInfo configBusiParamDocumentInfo) {
        CaseMainInfo caseMainInfo = caseMainInfoMapper.selectByPrimaryKey(saveDto.getCaseId());
        // 获取条线信息
        LineTerritoryInfoVo lineTerritoryInfoVo = sysDepartParamService.getLineInfoByOrgCodeAndLineCodeNumber(caseMainInfo.getCaseOrgCode(), caseMainInfo.getCaseDeptCode(), caseMainInfo.getLineCode());
        String lineDocNumber = lineTerritoryInfoVo.getLineDocNumber();
        //获取年度 “〔 〕”处填写年度
        String currentYear = caseMainInfo.getCaseNumber().substring(caseMainInfo.getCaseNumber().indexOf("〔"), caseMainInfo.getCaseNumber().indexOf("〕") + 1);

        //获取关联文书的记录（告知书或者决定书的记录）
        CaseDocumentRecord relationDocumentRecord = caseDocumentRecordMapper.selectByPrimaryKey(saveDto.getRelationDocumentId());
        ConfigBusiParamDocumentInfo relationConfigInfo = configBusiParamDocumentInfoService.getDetailByDocumentCatalogCode(relationDocumentRecord.getDocumentCatalogCode());

        //补正/更正文书的数量（带有文号的）
        int correctionDocNum = 0;
        //根据DocumentCatalogCode查询有文号的（告知书或者决定书），包含撤回和正常状态，不包括修改
        List<CaseDocumentRecord> relationDocRecordList = caseDocumentRecordService.getCaseDocumentRecordHasDocumentNumber(saveDto.getCaseId(), relationDocumentRecord.getDocumentCatalogCode());
        List<String> relationRecordIds = CollUtil.newArrayList();
        relationDocRecordList.forEach(relationRecord -> relationRecordIds.add(relationRecord.getId()));

        //根据（告知书或者决定书）的idList，查询出对应的补正/更正有多少条记录（有文号，包含撤回和正常状态，不包括修改）
        List<CaseDocumentRecord> caseDocumentRecordList = caseDocumentRecordService.getCaseCorrectDocumentRecordListFindNum(saveDto.getCaseId(), relationRecordIds, documentCatalogCode);
        if (ObjectUtil.isNotEmpty(caseDocumentRecordList)) {
            correctionDocNum = caseDocumentRecordList.size();
        }

        //获取立案审批表的文号
        CaseDocumentRecord caseDocumentRecord = caseDocumentRecordService.getCaseDocumentRecord(saveDto.getCaseId(), configBusiParamDocumentInfo.getDocumentNumberMatchCatalogCode());

        //立案的
        String docNum = caseDocumentRecord.getDocumentNumber();
        String docNumber = docNum.substring(docNum.indexOf("第") + 1, docNum.length() - 1);
        if (correctionDocNum > 0) {
            docNumber = docNumber + "-" + correctionDocNum;
        }
        //numAbbreviation的值{"CFJDS":"罚决补/更字","CFGZS":"罚告补/更字","CFGZSTZL":"罚听告补/更字"}
        String numAbbreviation = configBusiParamDocumentInfo.getDocumentNumberAbbreviation();
        numAbbreviation = JSONObject.parseObject(numAbbreviation).getString(relationConfigInfo.getDocumentKindCode());
        String documentNumber = lineDocNumber + numAbbreviation + currentYear + "第" + docNumber + "号";
        return documentNumber;
    }

    /**
     * 描述：送达回证打印后更新文书记录信息
     *
     * @param documentCatalogCode 文书目录编码
     * @param pdfUrl              送达回证文书pdf信息
     * @param pdfSealUrl          签章后送达回证文书pdf信息
     * @param caseId              案件id
     * @param isGetBlankDoc       是否获取空白文书
     * @param partyId             当事人id
     * @author xiangyuyu
     * @date 2022-03-12 16:00
     */
    private void updateDocumentRecordInfoAfterSentReceiptPrint(String documentCatalogCode, Map<String, String> pdfUrl, String pdfSealUrl, String caseId, String isGetBlankDoc, String partyId) {
        //先校验文书是否为送达回证
        ConfigBusiParamDocumentInfo configBusiParamDocumentInfo
                = configBusiParamDocumentInfoService.getDetailByDocumentCatalogCode(documentCatalogCode);
        if (ObjectUtils.isEmpty(configBusiParamDocumentInfo)) {
            throw new BusinessException("非法的文书目录编码：" + documentCatalogCode);
        }
        String documentKindCode = configBusiParamDocumentInfo.getDocumentKindCode();
        if (Constant.STRING_KIND_CODE_SDHZ.equals(documentKindCode)) {
            String sentReceiptPdfUrl = "";
            if (!ObjectUtils.isEmpty(pdfSealUrl)) {
                sentReceiptPdfUrl = pdfSealUrl;
            } else {
                if (ObjectUtils.isEmpty(pdfUrl) || pdfUrl.size() == 0) {
                } else {
                    sentReceiptPdfUrl = pdfUrl.get("fileUrl");
                    if (ObjectUtils.isEmpty(sentReceiptPdfUrl)) {
                        log.error("未找到送达回证文书pdf地址为空");
                    }
                }
            }
            //获取xx送达回证的文书记录
            CaseDocumentRecord caseDocumentRecord = caseDocumentRecordService.getCaseDocumentRecord(caseId, documentCatalogCode, partyId);
            if (!ObjectUtils.isEmpty(caseDocumentRecord)) {
                CaseDocumentRecord newRecord = new CaseDocumentRecord();
                newRecord.setId(caseDocumentRecord.getId());
                if (YesOrNoEnum.YES.getCode().equals(isGetBlankDoc)) {
                    newRecord.setDocumentUrlBlank(sentReceiptPdfUrl);
                } else {
                    newRecord.setDocumentUrl(sentReceiptPdfUrl);
                }
                caseDocumentRecordMapper.updateByPrimaryKeySelective(newRecord);
            }
        }
    }

    /**
     * 描述：强制执行申请书生成后发送至法院非诉执行立案申请
     *
     * @param saveDto 保存dto
     * @author shishengyao
     * @date 2022/04/10
     */
    private void nonLitigationExecute(StageDocCommonOperateSaveDto saveDto) {
        if ("QZZXSQS".equals(saveDto.getDocumentKindCode())) {
            CaseNonLitigationExecuteRequestDto requestDto = new CaseNonLitigationExecuteRequestDto();
            requestDto.setCaseId(saveDto.getCaseId());
            Map<String, Object> result = caseNonLitigationExecuteRecordService.nonLitigationExecuteRegister(requestDto);
            if (Constant.STRING_FAIL_EN.equals(result.get("code"))) {
                throw new BusinessException(result.get("errorMsg").toString());
            }
        }
    }

    /**
     * 根据配置更新相关数据
     *
     * @param saveDto
     * @return
     * @author liyafeng
     * @date 2022/3/1
     */
    private void operateBusiTableByDocumentCatalogCode(StageDocCommonOperateSaveDto saveDto) {
        List<BusiTableOperateVo> busiTableOperateVoList = configBusiParamDocumentColumnMapper.selectTableNameListByDocumentCatalogCode(saveDto.getDocumentCatalogCode());
        if (null != busiTableOperateVoList && busiTableOperateVoList.size() > 0) {
            for (BusiTableOperateVo busiTableOperateVo : busiTableOperateVoList) {
                if (ObjectUtil.isNotEmpty(busiTableOperateVo.getDocumentTemplateType()) && !busiTableOperateVo.getDocumentTemplateType().contains(DocumentTemplateKindEnum.STANDARD_TEMPLATE.getCode())) {
                    continue;
                }
                Example example = new Example(ConfigBusiParamDocumentColumn.class);
                example.createCriteria().andEqualTo("documentCatalogCode", saveDto.getDocumentCatalogCode()).andEqualTo("busiTableNameEn", busiTableOperateVo.getBusiTableNameEn()).andEqualTo("busiOperateType", busiTableOperateVo.getBusiOperateType());
                List<ConfigBusiParamDocumentColumn> configBusiParamDocumentColumnList = configBusiParamDocumentColumnMapper.selectByExample(example);

                if ("U".equals(busiTableOperateVo.getBusiOperateType())) {
                    updateBusiTable(busiTableOperateVo, busiTableOperateVoList, saveDto, configBusiParamDocumentColumnList);
                }
                if ("I,U".equals(busiTableOperateVo.getBusiOperateType())) {
                    //先判断是否存在
                    String selectSql = "select count(1) from upcase." + busiTableOperateVo.getBusiTableNameEn() + " where case_id='" + saveDto.getCaseId() + "'";
                    ConfigBusiParamDocumentInfo configBusiParamDocumentInfo = configBusiParamDocumentInfoService.getDetailByDocumentCatalogCode(saveDto.getDocumentCatalogCode());
                    String documentKindCode = configBusiParamDocumentInfo.getDocumentKindCode();
                    if (Constant.STRING_KIND_CODE_SDDZQRS.equals(documentKindCode)) {
                        selectSql = selectSql.concat(" and party_id = '" + saveDto.getPartyId() + "'");
                    }
                    if (CaseStatusChangeTypeEnum.isCaseChangeDocEnum(documentKindCode)) {
                        selectSql = selectSql.concat(" and case_change_type = '" + CaseStatusChangeTypeEnum.getEnumByDocumentKindCode(documentKindCode).getCode() + "'");
                    }
                    int num = configBusiParamDocumentColumnMapper.executeSelectNumSql(selectSql);
                    if (num > 0) {
                        //存在则更新
                        updateBusiTable(busiTableOperateVo, busiTableOperateVoList, saveDto, configBusiParamDocumentColumnList);

                    } else {
                        //不存在则插入
                        Map<String, String> insertMap = new HashMap<>();
                        //组装map
                        for (ConfigBusiParamDocumentColumn configBusiParamDocumentColumn : configBusiParamDocumentColumnList) {
                            if ("id".equals(configBusiParamDocumentColumn.getBusiOperateCondition())) {
                                insertMap.put(configBusiParamDocumentColumn.getBusiColumnEn(), StringUtils.uuid());
                                continue;
                            }
                            if ("case_id".equals(configBusiParamDocumentColumn.getBusiOperateCondition())) {
                                insertMap.put(configBusiParamDocumentColumn.getBusiColumnEn(), saveDto.getCaseId());
                                continue;
                            }
                            if ("document_catalog_code".equals(configBusiParamDocumentColumn.getBusiOperateCondition())) {
                                insertMap.put(configBusiParamDocumentColumn.getBusiColumnEn(), saveDto.getDocumentCatalogCode());
                                continue;
                            }
                            if ("create_time".equals(configBusiParamDocumentColumn.getBusiOperateCondition())) {
                                insertMap.put(configBusiParamDocumentColumn.getBusiColumnEn(), DateUtils.formatDate(new Date(), "yyyy-MM-dd HH:mm:ss"));
                                continue;
                            }
                            //---送达方式及地址确认书使用start---
                            if ("party_id".equals(configBusiParamDocumentColumn.getBusiOperateCondition())) {
                                insertMap.put(configBusiParamDocumentColumn.getBusiColumnEn(), saveDto.getPartyId());
                                continue;
                            }
                            /*if ("status".equals(configBusiParamDocumentColumn.getBusiOperateCondition())) {
                                insertMap.put(configBusiParamDocumentColumn.getBusiColumnEn(), null);//默认设置为空，签字确认后修改为1
                                continue;
                            }*/
                            //---送达方式及地址确认书使用end---

                            String columnValue = "";
                            try {
                                //columnValue = saveDto.getDataMap().get(configBusiParamDocumentColumn.getDocumentTemplateFieldEn()).toString();
                                columnValue = MapUtils.getString(saveDto.getDataMap(), configBusiParamDocumentColumn.getDocumentTemplateFieldEn(), "");
                            } catch (Exception e) {
                                throw new BusinessException(configBusiParamDocumentColumn.getDocumentTemplateFieldCn() + "为空");
                            }
                            insertMap.put(configBusiParamDocumentColumn.getBusiColumnEn(), columnValue);
                        }
                        //生成INSERT INTO table(field1,field2) 部分
                        StringBuffer sbField = new StringBuffer();
                        //生成VALUES('value1','value2') 部分
                        StringBuffer sbValue = new StringBuffer();
                        sbField.append("INSERT INTO  upcase." + busiTableOperateVo.getBusiTableNameEn() + "(");
                        for (Map.Entry<String, String> entry : insertMap.entrySet()) {
                            String mapKey = entry.getKey();
                            String mapValue = entry.getValue();
                            mapValue = mapValue.replace("'", "''");
                            sbField.append(mapKey + ",");
                            sbValue.append("'" + mapValue + "',");
                        }
                        sbField = sbField.deleteCharAt(sbField.length() - 1);
                        sbValue = sbValue.deleteCharAt(sbValue.length() - 1);
                        String insertSql = sbField.toString() + ") VALUES(" + sbValue.toString() + ")";
                        configBusiParamDocumentColumnMapper.executeInsertSql(insertSql);
                    }


                }
            }
        }
    }

    /**
     * 更新操作
     *
     * @param busiTableOperateVo
     * @param busiTableOperateVoList
     * @param saveDto
     * @param configBusiParamDocumentColumnList
     * @return
     * @author liyafeng
     * @date 2022/3/11
     */
    private void updateBusiTable(BusiTableOperateVo busiTableOperateVo, List<BusiTableOperateVo> busiTableOperateVoList, StageDocCommonOperateSaveDto saveDto, List<ConfigBusiParamDocumentColumn> configBusiParamDocumentColumnList) {
        String tableName = busiTableOperateVo.getBusiTableNameEn();
        String caseId = saveDto.getCaseId();
        String setSql = "";
        String sqlCondition = "";
        for (ConfigBusiParamDocumentColumn configBusiParamDocumentColumn : configBusiParamDocumentColumnList) {
            //BusiOperateCondition 不为空 此字段不更新
            if (StringUtils.isNotBlank(configBusiParamDocumentColumn.getBusiOperateCondition())) {
                if ("party_id".equals(configBusiParamDocumentColumn.getBusiOperateCondition())) {
                    sqlCondition += " and party_id = '" + saveDto.getPartyId() + "'";
                }
                continue;
            }
            if (ObjectUtil.isNotEmpty(configBusiParamDocumentColumn.getDocumentTemplateType()) && !configBusiParamDocumentColumn.getDocumentTemplateType().contains(DocumentTemplateKindEnum.STANDARD_TEMPLATE.getCode())) {
                continue;
            }
            String columnValue = "";
            try {
                columnValue = saveDto.getDataMap().get(configBusiParamDocumentColumn.getDocumentTemplateFieldEn()).toString();
                columnValue = columnValue.replace("'", "''");
            } catch (Exception e) {
                //前端没有传key值，此字段不更新
                if (saveDto.getDataMap().get(configBusiParamDocumentColumn.getDocumentTemplateFieldEn()) == null)
                    continue;

                throw new BusinessException(configBusiParamDocumentColumn.getDocumentTemplateFieldCn() + "为空");
            }
            if (StringUtils.isBlank(setSql)) {
                setSql = configBusiParamDocumentColumn.getBusiColumnEn() + "='" + columnValue + "'";
            } else {
                setSql = setSql + "," + configBusiParamDocumentColumn.getBusiColumnEn() + "='" + columnValue + "'";
            }
        }
        String updateSql = "update upcase." + tableName + " set " + setSql + " where " + " case_id='" + caseId + "'";

        ConfigBusiParamDocumentInfo configBusiParamDocumentInfo = configBusiParamDocumentInfoService.getDetailByDocumentCatalogCode(saveDto.getDocumentCatalogCode());
        if (Constant.STRING_KIND_CODE_SDDZQRS.equals(configBusiParamDocumentInfo.getDocumentKindCode())) {
            updateSql = updateSql.concat(" and party_id = '" + saveDto.getPartyId() + "'");
        }
        //案件操作文书
        if (CaseStatusChangeTypeEnum.isCaseChangeDocEnum(configBusiParamDocumentInfo.getDocumentKindCode())) {
            updateSql = updateSql.concat(" and case_change_type = '" + CaseStatusChangeTypeEnum.getEnumByDocumentKindCode(configBusiParamDocumentInfo.getDocumentKindCode()).getCode() + "'");
        }
        updateSql = updateSql.concat(sqlCondition);
        configBusiParamDocumentColumnMapper.executeUpdateSql(updateSql);
    }


    /**
     * 根据文书目录编码获取法人或个人文件模板code
     *
     * @param documentCatalogCode
     * @return {@link String}
     * @author liyafeng
     * @date 2022/3/1
     */
    @Override
    public String getTemplateCodeByDocumentCatalogCode(String documentCatalogCode, String caseId, Map<String, Object> paramMap, String partyId) {
        // 如果已有记录，取原来的文书目录编码
        CaseDocumentRecord recordInfo = caseDocumentRecordService.getCaseDocumentRecord(caseId, documentCatalogCode, partyId);
        if (ObjectUtil.isNotEmpty(recordInfo) && ObjectUtil.isNotEmpty(recordInfo.getDocumentTemplateCode())) {
            return recordInfo.getDocumentTemplateCode();
        }
        //没有的话查询目录编码
        CaseMainInfoVo caseMainInfoVo = caseMainInfoMapper.selectCaseMainInfo(caseId);
        ConfigBusiParamDocumentInfo detailResult = configBusiParamDocumentInfoService.getDetailByDocumentCatalogCode(documentCatalogCode);
        String templateCode = detailResult.getTemplatePersonCode();
        List<String> fastCaseList = Arrays.asList(CaseTypeEnum.SIMPLE_QUICK.getCode(), CaseTypeEnum.FAST_PROCEDURE.getCode());
        if (ObjectUtil.isEmpty(caseMainInfoVo) ||
                (CaseStatusEnum.PUNISH_NO_REGISTER.getCode().equals(caseMainInfoVo.getCaseStatus()) && ApiVisitDataSourceEnum.PUNISH_AY.getCode().equals(caseMainInfoVo.getDataSource()))) {
            return detailResult.getTemplatePersonCode();
        }
        String caseType = caseMainInfoVo.getCaseType();

        if (ObjectUtil.isNotEmpty(detailResult)) {
            List<CasePartiesInfoVo> casePartiesRecordVos = casePartiesRecordService.getCasePartiesInfoVo(caseId, partyId);
            //根据当事人类型获取对应的模板
            if (null != casePartiesRecordVos && casePartiesRecordVos.size() > 0) {
                CasePartiesInfoVo casePartiesRecordVo = casePartiesRecordVos.get(0);
                if ("1".equals(casePartiesRecordVo.getPartyType())) {
                    //个人
                    templateCode = detailResult.getTemplatePersonCode();
                    if (fastCaseList.contains(caseType) && Constant.STRING_1.equals(detailResult.getIsFastCase())) {
                        templateCode = detailResult.getFastTemplatePersonCode();
                    }
                } else {
                    //法人

                    templateCode = detailResult.getTemplateLegalCode();
                    if (fastCaseList.contains(caseType) && Constant.STRING_1.equals(detailResult.getIsFastCase())) {
                        templateCode = detailResult.getFastTemplateLegalCode();
                    }
                }
            }
        }
        return templateCode;
    }

    /**
     * 操作文书记录表 TODO 必须优化
     *
     * @param documentCatalogCode  文件目录的代码
     * @param caseMainInfo
     * @param convertedPdfUrl
     * @param documentNumber
     * @param paramMap
     * @param pdfSealUrl           pdf印网址
     * @param sentDeadline         送达截止日期
     * @param partyId              当事人id
     * @param documentTemplateType 文书模板类型
     * @return int
     * @author shishengyao
     * @date 2022/03/14
     */
    private Map<String, Object> operateCaseDocumentRecord(String caseAssistId, String documentCatalogCode, CaseMainInfo caseMainInfo, String convertedPdfUrl, String documentNumber, Map<String, Object> paramMap, String pdfSealUrl, LocalDate sentDeadline, String isMultipleDoc, String belongDocumentId, String partyId, String documentTemplateType, zlbCaseDocumentRecordDto zlbCaseDocumentRecord, String isEditFile, String docId, String templateCode) {

        String handleType = caseMainInfo.getHandleType();
        Map<String, Object> operateMap = new HashMap<>();
        //根据目录编码查询
        ConfigBusiParamDocumentInfo configBusiParamDocumentInfo = configBusiParamDocumentInfoService.getDetailByDocumentCatalogCode(documentCatalogCode);
        String documentKindCode = configBusiParamDocumentInfo.getDocumentKindCode();
        String caseId = caseMainInfo.getId();
        if (ObjectUtil.isEmpty(templateCode)) {
            // todo 文书目前不区分个人法人，统一取个人模板
            templateCode = getTemplateCodeByDocumentCatalogCode(documentCatalogCode, caseId, null, partyId);
        }

        int num = 0;
        UserDTO userDTO = null;
        try {
            userDTO = UserUtil.getUserInfo();
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (ObjectUtils.isEmpty(userDTO)) {
            userDTO = new UserDTO();
            userDTO.setUserId(0L);
            userDTO.setRealName("系统");
        }
        //判断文书记录是否存在
        List<CaseDocumentRecord> caseDocumentRecords = new ArrayList<>();
        if (StringUtils.isNotBlank(docId)) {
            CaseDocumentRecord caseDocumentRecord = caseDocumentRecordMapper.selectByPrimaryKey(docId);
            if (!ObjectUtils.isEmpty(caseDocumentRecord)) {
                caseDocumentRecords.add(caseDocumentRecord);
            }
        }
        boolean isNeedPartyIdInfo = false;
        if (sentRelatedNeedPartyIdDocumentKindCodeList.contains(documentKindCode)) {
            isNeedPartyIdInfo = true;
        }
        if (ObjectUtils.isEmpty(caseDocumentRecords)) {
            Example example = new Example(CaseDocumentRecord.class);
            Example.Criteria c = example.createCriteria();
            if (StringUtils.isBlank(isMultipleDoc) || Constant.STRING_0.equals(isMultipleDoc) || StringUtils.isBlank(belongDocumentId)) {
                if (DocumentKindEnum.DOC_KIND_LASPB.getCode().equals(configBusiParamDocumentInfo.getDocumentKindCode())) {
                    c.andEqualTo("caseId", caseMainInfo.getId()).andEqualTo("documentCatalogCode", documentCatalogCode);
                } else {
                    //非多条文书记录
                    c.andEqualTo("caseId", caseMainInfo.getId()).andEqualTo("documentCatalogCode", documentCatalogCode);
                    if (!ObjectUtils.isEmpty(partyId)) {


                        if (!HandleTypeEnum.MERGE_PUNISH.getCode().equals(handleType) || isNeedPartyIdInfo) {
                            c.andEqualTo("partyId", partyId);
                        }
                    }
                }
            } else if (StringUtils.isNotBlank(belongDocumentId)) {
                c.andEqualTo("caseId", caseMainInfo.getId()).andEqualTo("documentCatalogCode", documentCatalogCode).andEqualTo("id", belongDocumentId);
            }
            if (!Constant.STRING_1.equals(isEditFile)) {
                c.andIn("documentRecordStatus", Arrays.asList(DocumentRecordStatusEnum.NORMAL.getCode(), DocumentRecordStatusEnum.DRAFT.getCode()));
            } else {
                c.andEqualTo("documentRecordStatus", Constant.STRING_4);
            }
            caseDocumentRecords = caseDocumentRecordMapper.selectByExample(example);
        }
        //获取副（子）流程主信息
        CaseAssistMainInfo caseAssistMainInfo = new CaseAssistMainInfo();
        if (StringUtils.isNotBlank(caseAssistId)) {
            caseAssistMainInfo = caseAssistMainInfoService.doGetCaseAssistMainInfoById(caseAssistId);
        }
        if ((StringUtils.isBlank(isMultipleDoc) || Constant.STRING_0.equals(isMultipleDoc)) || (StringUtils.isNotBlank(belongDocumentId) && Constant.STRING_1.equals(isMultipleDoc))) {
            // 特殊处理中止审批表
            boolean suspendUpdateFlag = true;
            if (null != caseDocumentRecords && ObjectUtil.isEmpty(belongDocumentId)) {
                if (documentKindCode.equals(DocumentKindEnum.DOC_KIND_CQZZQZZXSQB.getCode())
                        || documentKindCode.equals(DocumentKindEnum.DOC_KIND_DT1SQGZGSSPB.getCode())) {
                    List<CaseDocumentRecord> caseDocumentRecordList = new ArrayList<>();
                    for (CaseDocumentRecord caseDocumentRecord : caseDocumentRecords) {
                        if (caseDocumentRecord.getDocumentApprovalStatus().equals(DocumentStatusEnum.CHECK_END.getCode())) {
                            suspendUpdateFlag = false;
                            break;
                        } else {
                            caseDocumentRecordList.add(caseDocumentRecord);
                        }
                    }
                    if (suspendUpdateFlag) {
                        caseDocumentRecords = caseDocumentRecordList;
                    }
                }
            }
            if (null != caseDocumentRecords && caseDocumentRecords.size() > 0 && suspendUpdateFlag) {
                //不为空，则添加历史，更新记录
                for (CaseDocumentRecord caseDocumentRecord : caseDocumentRecords) {
                    //添加历史
                    CaseDocumentRecordHis caseDocumentRecordHis = new CaseDocumentRecordHis();
                    BeanUtils.copyProperties(caseDocumentRecord, caseDocumentRecordHis);
                    //增加创建时间设置
                    try {
                        Date createTime = Date.from(caseDocumentRecord.getDocumentCreateTime().atZone(ZoneId.systemDefault()).toInstant());
                        caseDocumentRecordHis.setDocumentCreateTime(createTime);
                    } catch (Exception e) {
                    }
                    caseDocumentRecordHis.setId(StringUtils.uuid());
                    caseDocumentRecordHis.setRecordId(caseDocumentRecord.getId());
                    caseDocumentRecordHis.setOp("update");
                    caseDocumentRecordHis.setHisCreateTime(new Date());
                    caseDocumentRecordHisMapper.insert(caseDocumentRecordHis);
                    //更新文书记录表
                    CaseDocumentRecord updateCaseDocumentRecord = new CaseDocumentRecord();
                    updateCaseDocumentRecord.setId(caseDocumentRecord.getId());
                    updateCaseDocumentRecord.setDocumentUrl(convertedPdfUrl);
                    //updateCaseDocumentRecord.setDocumentCreateTime(LocalDateTime.now());
                    //updateCaseDocumentRecord.setDocumentApprovalStatus(saveDto.getDocumentApprovalStatus());
                    if (!Constant.STRING_KIND_CODE_SDHZ.equals(documentKindCode) || !ObjectUtils.isEmpty(pdfSealUrl)) {
                        updateCaseDocumentRecord.setDocumentUrlAfterSeal(pdfSealUrl);
                    }
                    updateCaseDocumentRecord.setSentDeadline(sentDeadline);
                    updateCaseDocumentRecord.setDocumentNumber(documentNumber);
                    updateCaseDocumentRecord.setDocumentContent(JSONObject.toJSON(paramMap).toString());
                    if (!ObjectUtils.isEmpty(partyId) && (!HandleTypeEnum.MERGE_PUNISH.getCode().equals(handleType) || isNeedPartyIdInfo)) {
                        updateCaseDocumentRecord.setPartyId(partyId);//设置当事人id
                    }

                    if (DocumentRecordStatusEnum.DRAFT.getCode().equals(caseDocumentRecord.getDocumentRecordStatus())) {
                        //生成默认待提交状态
                        if ("1".equals(configBusiParamDocumentInfo.getIsApprove())) {
                            updateCaseDocumentRecord.setDocumentApprovalStatus(DocumentStatusEnum.WAIT_TO_SUBMIT.getCode());
                            updateCaseDocumentRecord.setDocumentAuditStatus("notSubmit");
                        }
                        if ("1".equals(configBusiParamDocumentInfo.getIsSend())) {
                            updateCaseDocumentRecord.setDocumentSentStatus(DocumentStatusEnum.WAIT_TO_SEND.getCode());
                        }
                        if (BusinessContextUtil.documentNeedConfirm(configBusiParamDocumentInfo)) {
                            updateCaseDocumentRecord.setDocumentSignstampedStatus(DocumentStatusEnum.WAIT_TO_CONFIRM.getCode());
                        }
                        if (!ObjectUtils.isEmpty(partyId) && partyId.length() == 32) {
                            if (StringUtils.isNotBlank(caseAssistId)) {
                                updateCaseDocumentRecord.setCaseStageName(caseAssistMainInfo.getCaseAssistFlowName());
                                updateCaseDocumentRecord.setCaseStageCode(caseAssistMainInfo.getCaseAssistFlowCode());
                                updateCaseDocumentRecord.setCaseLinkCode(caseAssistMainInfo.getCaseAssistCurrentLinkCode());
                                updateCaseDocumentRecord.setCaseLinkName(caseAssistMainInfo.getCaseAssistCurrentLinkName());
                            } else {
                                WorkFlowRollSubMainInfo workFlowRollSubMainInfo = workFlowRollSubMainInfoService.getWorkFlowRollSubMainInfo(caseMainInfo.getId(), partyId);
                                if (!ObjectUtils.isEmpty(workFlowRollSubMainInfo)) { //简易处罚没有工作流数据
                                    updateCaseDocumentRecord.setCaseStageName(workFlowRollSubMainInfo.getWorkCurrentStageName());
                                    updateCaseDocumentRecord.setCaseStageCode(workFlowRollSubMainInfo.getWorkCurrentStageCode());
                                    updateCaseDocumentRecord.setCaseLinkCode(workFlowRollSubMainInfo.getWorkCurrentLinkCode());
                                    updateCaseDocumentRecord.setCaseLinkName(workFlowRollSubMainInfo.getWorkCurrentLinkName());
                                }
                            }
                        } else {
                            updateCaseDocumentRecord.setCaseStageName(caseMainInfo.getCaseCurrentStageName());
                            updateCaseDocumentRecord.setCaseStageCode(caseMainInfo.getCaseCurrentStageCode());
                            updateCaseDocumentRecord.setCaseLinkCode(caseMainInfo.getCaseCurrentLinkCode());
                            updateCaseDocumentRecord.setCaseLinkName(caseMainInfo.getCaseCurrentLinkName());
                        }
                    }
                    //需要重新确认的文书类型
                    List<String> needReConfirmKindCode = Arrays.asList(DocumentKindEnum.DOC_KIND_SDDZQRS.getCode(),
                            DocumentKindEnum.DOC_KIND_XWTZS.getCode(),
                            DocumentKindEnum.DOC_KIND_ZLGZTZS.getCode(),
                            DocumentKindEnum.DOC_KIND_CYQZTZS.getCode(),
                            DocumentKindEnum.DOC_KIND_CYQZWPCLTZS.getCode(),
                            DocumentKindEnum.DOC_KIND_ZLTZWFXWTZS.getCode());
                    //送达地址确认书,询问通知书及责令改正通知书更新后需重新签字确认
                    if (needReConfirmKindCode.contains(documentKindCode)) {
                        //设置待确认
                        if (BusinessContextUtil.documentNeedConfirm(configBusiParamDocumentInfo)) {
                            updateCaseDocumentRecord.setDocumentSignstampedStatus(DocumentStatusEnum.WAIT_TO_CONFIRM.getCode());
                        }
                        updateCaseDocumentRecord.setDocumentUrlAfterSign(null);
                        updateCaseDocumentRecord.setDocumentCreateTime(LocalDateTime.now());
                        //设置签署文书为删除状态
                        Example appendixExample = new Example(CaseAppendixRecord.class);
                        appendixExample.createCriteria().andEqualTo("caseId", caseDocumentRecord.getCaseId())
                                .andEqualTo("documentCatalogCode", caseDocumentRecord.getDocumentCatalogCode())
                                .andEqualTo("isDelete", "0").andEqualTo("appendixStatus", "1")
                                .andEqualTo("partyId", caseDocumentRecord.getPartyId());
                        List<CaseAppendixRecord> caseAppendixRecords = caseAppendixRecordMapper.selectByExample(appendixExample);
                        if (!ObjectUtils.isEmpty(caseAppendixRecords)) {
                            caseAppendixRecords.forEach(e -> {
                                e.setIsDelete(Constant.STRING_1);
                                caseAppendixRecordMapper.updateByPrimaryKeySelective(e);
                            });
                        }
                        //送达地址确认书需修改送达记录为失效状态
                        if (DocumentKindEnum.DOC_KIND_SDDZQRS.getCode().equals(documentKindCode)) {
                            Example queryExample = new Example(CaseDocumentSendinfoConfirm.class);
                            queryExample.createCriteria().andEqualTo("caseId", caseMainInfo.getId())
                                    .andEqualTo("partyId", caseDocumentRecord.getPartyId())
                                    .andEqualTo("status", Constant.INTEGER_1);
                            List<CaseDocumentSendinfoConfirm> sendInfoConfirmList
                                    = caseDocumentSendinfoConfirmMapper.selectByExample(queryExample);
                            if (!ObjectUtils.isEmpty(sendInfoConfirmList)) {
                                for (CaseDocumentSendinfoConfirm caseDocumentSendinfoConfirm : sendInfoConfirmList) {
                                    caseDocumentSendinfoConfirm.setStatus(null);
                                    caseDocumentSendinfoConfirmMapper.updateByPrimaryKey(caseDocumentSendinfoConfirm);
                                }
                            }
                        }
                    }
                    if (!Constant.STRING_1.equals(isEditFile)) {
                        updateCaseDocumentRecord.setDocumentRecordStatus(DocumentRecordStatusEnum.NORMAL.getCode());//设置文书为正常状态
                    }
                    if (!ObjectUtils.isEmpty(documentTemplateType)) { //设置模板类型
                        caseDocumentRecord.setDocumentTemplateType(documentTemplateType);
                    }
                    caseDocumentRecord.setCreateUserName(userDTO.getRealName());
                    caseDocumentRecord.setCreateUserId(userDTO.getUserId().toString());
                    num = caseDocumentRecordMapper.updateByPrimaryKeySelective(updateCaseDocumentRecord);
                    operateMap.put("num", num);
                    operateMap.put("documentId", caseDocumentRecord.getId());
                }
                return operateMap;
            } else {
                CaseDocumentRecord caseDocumentRecord = new CaseDocumentRecord();
                caseDocumentRecord.setCaseId(caseMainInfo.getId());
                caseDocumentRecord.setId(StringUtils.uuid());
                caseDocumentRecord.setDocumentCatalogCode(documentCatalogCode);
                caseDocumentRecord.setDocumentUrl(convertedPdfUrl);
                caseDocumentRecord.setSentDeadline(sentDeadline);
                caseDocumentRecord.setDocumentCreateTime(LocalDateTime.now());
                caseDocumentRecord.setDocumentContent(JSONObject.toJSON(paramMap).toString());
                //生成默认待提交状态
                if ("1".equals(configBusiParamDocumentInfo.getIsApprove())) {
                    caseDocumentRecord.setDocumentApprovalStatus(DocumentStatusEnum.WAIT_TO_SUBMIT.getCode());
                    caseDocumentRecord.setDocumentAuditStatus("notSubmit");
                }
                if ("1".equals(configBusiParamDocumentInfo.getIsSend())) {
                    caseDocumentRecord.setDocumentSentStatus(DocumentStatusEnum.WAIT_TO_SEND.getCode());
                }
                if (BusinessContextUtil.documentNeedConfirm(configBusiParamDocumentInfo)) {
                    caseDocumentRecord.setDocumentSignstampedStatus(DocumentStatusEnum.WAIT_TO_CONFIRM.getCode());
                }
                caseDocumentRecord.setDocumentNumber(documentNumber);
                caseDocumentRecord.setCreateUserName(userDTO.getRealName());
                caseDocumentRecord.setCreateUserId(userDTO.getUserId().toString());
                caseDocumentRecord.setDocumentUrlAfterSeal(pdfSealUrl);
                caseDocumentRecord.setDocumentRecordStatus(DocumentRecordStatusEnum.NORMAL.getCode());//设置文书为正常状态
                if (!ObjectUtils.isEmpty(documentTemplateType)) { //设置模板类型
                    caseDocumentRecord.setDocumentTemplateType(documentTemplateType);
                }

                if (!ObjectUtils.isEmpty(partyId)) {
                    //设置当事人id
                    caseDocumentRecord.setPartyId(partyId);
                }

                if (!ObjectUtils.isEmpty(partyId) && partyId.length() == 32) { //TODO 不知道这里为什么这么写，太奇怪了
                    if (StringUtils.isNotBlank(caseAssistId)) {
                        caseDocumentRecord.setCaseStageName(caseAssistMainInfo.getCaseAssistFlowName());
                        caseDocumentRecord.setCaseStageCode(caseAssistMainInfo.getCaseAssistFlowCode());
                        caseDocumentRecord.setCaseLinkCode(caseAssistMainInfo.getCaseAssistCurrentLinkCode());
                        caseDocumentRecord.setCaseLinkName(caseAssistMainInfo.getCaseAssistCurrentLinkName());
                    } else {
                        WorkFlowRollSubMainInfo workFlowRollSubMainInfo = workFlowRollSubMainInfoService.getWorkFlowRollSubMainInfo(caseMainInfo.getId(), partyId);
                        if (!ObjectUtils.isEmpty(workFlowRollSubMainInfo)) { //简易处罚没有工作流数据
                            caseDocumentRecord.setCaseStageName(workFlowRollSubMainInfo.getWorkCurrentStageName());
                            caseDocumentRecord.setCaseStageCode(workFlowRollSubMainInfo.getWorkCurrentStageCode());
                            caseDocumentRecord.setCaseLinkCode(workFlowRollSubMainInfo.getWorkCurrentLinkCode());
                            caseDocumentRecord.setCaseLinkName(workFlowRollSubMainInfo.getWorkCurrentLinkName());
                        }
                    }

                } else {
                    caseDocumentRecord.setCaseStageName(caseMainInfo.getCaseCurrentStageName());
                    caseDocumentRecord.setCaseStageCode(caseMainInfo.getCaseCurrentStageCode());
                    caseDocumentRecord.setCaseLinkCode(caseMainInfo.getCaseCurrentLinkCode());
                    caseDocumentRecord.setCaseLinkName(caseMainInfo.getCaseCurrentLinkName());
                }
                if (StringUtils.isNotBlank(caseAssistId)) {
                    caseDocumentRecord.setCaseAssistId(caseAssistId);
                }
                caseDocumentRecord.setDocumentTemplateCode(templateCode);
                // 通过浙里办增加的送达确认书
                zlbSaveCaseDocumentRecord(zlbCaseDocumentRecord, caseDocumentRecord, configBusiParamDocumentInfo);
                num = caseDocumentRecordMapper.insert(caseDocumentRecord);
                operateMap.put("num", num);
                operateMap.put("documentId", caseDocumentRecord.getId());
                return operateMap;
            }
        }
        CaseDocumentRecord caseDocumentRecord = new CaseDocumentRecord();
        caseDocumentRecord.setCaseId(caseMainInfo.getId());
        caseDocumentRecord.setId(StringUtils.uuid());
        if (StringUtils.isNotBlank(caseAssistId)) {
            caseDocumentRecord.setCaseStageName(caseAssistMainInfo.getCaseAssistFlowName());
            caseDocumentRecord.setCaseStageCode(caseAssistMainInfo.getCaseAssistFlowCode());
            caseDocumentRecord.setCaseLinkCode(caseAssistMainInfo.getCaseAssistCurrentLinkCode());
            caseDocumentRecord.setCaseLinkName(caseAssistMainInfo.getCaseAssistCurrentLinkName());
        } else {
            caseDocumentRecord.setCaseStageName(caseMainInfo.getCaseCurrentStageName());
            caseDocumentRecord.setCaseStageCode(caseMainInfo.getCaseCurrentStageCode());
            caseDocumentRecord.setCaseLinkCode(caseMainInfo.getCaseCurrentLinkCode());
            caseDocumentRecord.setCaseLinkName(caseMainInfo.getCaseCurrentLinkName());
        }
        caseDocumentRecord.setDocumentCatalogCode(documentCatalogCode);
        caseDocumentRecord.setDocumentUrl(convertedPdfUrl);
        caseDocumentRecord.setSentDeadline(sentDeadline);
        caseDocumentRecord.setDocumentCreateTime(LocalDateTime.now());
        caseDocumentRecord.setDocumentContent(JSONObject.toJSON(paramMap).toString());
        //生成默认待提交状态
        if ("1".equals(configBusiParamDocumentInfo.getIsApprove())) {
            caseDocumentRecord.setDocumentApprovalStatus(DocumentStatusEnum.WAIT_TO_SUBMIT.getCode());
            caseDocumentRecord.setDocumentAuditStatus("notSubmit");
        }
        if ("1".equals(configBusiParamDocumentInfo.getIsSend())) {
            caseDocumentRecord.setDocumentSentStatus(DocumentStatusEnum.WAIT_TO_SEND.getCode());
        }
        if (BusinessContextUtil.documentNeedConfirm(configBusiParamDocumentInfo)) {
            caseDocumentRecord.setDocumentSignstampedStatus(DocumentStatusEnum.WAIT_TO_CONFIRM.getCode());
        }
        caseDocumentRecord.setDocumentNumber(documentNumber);
        caseDocumentRecord.setCreateUserName(userDTO.getRealName());
        caseDocumentRecord.setCreateUserId(userDTO.getUserId().toString());
        caseDocumentRecord.setDocumentUrlAfterSeal(pdfSealUrl);
        caseDocumentRecord.setDocumentRecordStatus(DocumentRecordStatusEnum.NORMAL.getCode());//设置文书为正常状态
        if (!ObjectUtils.isEmpty(partyId)) {
            //设置当事人id
            caseDocumentRecord.setPartyId(partyId);
        }
        if (!ObjectUtils.isEmpty(documentTemplateType)) { //设置模板类型
            caseDocumentRecord.setDocumentTemplateType(documentTemplateType);
        }
        if (StringUtils.isNotBlank(caseAssistId)) {
            caseDocumentRecord.setCaseAssistId(caseAssistId);
        }
        caseDocumentRecord.setDocumentTemplateCode(templateCode);
        zlbSaveCaseDocumentRecord(zlbCaseDocumentRecord, caseDocumentRecord, configBusiParamDocumentInfo);
        num = caseDocumentRecordMapper.insert(caseDocumentRecord);

        operateMap.put("num", num);
        operateMap.put("documentId", caseDocumentRecord.getId());
        return operateMap;
    }

    private void zlbSaveCaseDocumentRecord(zlbCaseDocumentRecordDto zlbCaseDocumentRecord, CaseDocumentRecord caseDocumentRecord, ConfigBusiParamDocumentInfo configBusiParamDocumentInfo) {
        if (!ObjectUtils.isEmpty(zlbCaseDocumentRecord)) {
            String zlbType = zlbCaseDocumentRecord.getZlbType();
            if (StringUtils.isNotBlank(zlbType) && Constant.STRING_1.equals(zlbType)) {
                if (BusinessContextUtil.documentNeedConfirm(configBusiParamDocumentInfo)) {
                    // 送达文书的情况下为待填写
                    caseDocumentRecord.setDocumentSignstampedStatus(DocumentStatusEnum.WAIT_TO_SIGN.getCode());
                    // 标记为2使用pc列表，不在浙里办端展示
                    caseDocumentRecord.setZlbService(Constant.STRING_2);
                }
            }
        }
    }

    /**
     * 获取文书html和配置字段公共方法
     *
     * @param request
     * @return {@link Result< String>}
     * @author liyafeng
     * @date 2022/2/18
     */
    @Override
    public DocumentCommonFormHtmlVo getDocumentFormHtml(StageDocCommonHtmlRequest request) {
        if (StringUtils.isNotEmpty(request.getDocumentTemplateCode())) {
            return getDocBaseInfoByDocumentTemplateCode(request);
        }
        DocumentCommonFormHtmlVo vo = new DocumentCommonFormHtmlVo();
        String templateCode = "";
        CaseDocumentRecord recordInfo = caseDocumentRecordService.getCaseDocumentRecord(request.getCaseId(), request.getDocumentCatalogCode(), request.getPartyId());
        if (ObjectUtil.isNotEmpty(recordInfo) && ObjectUtil.isNotEmpty(recordInfo.getDocumentContent())) {
            templateCode = recordInfo.getDocumentTemplateCode();
            ConfigBusiParamDocumentInfo configBusiParamDocumentInfo = configBusiParamDocumentInfoService.getDetailByDocumentCatalogCode(request.getDocumentCatalogCode());
            //责令改正通知书审批表 重复制作校验
            if (Constant.STRING_KIND_CODE_ZLGZTZSSPB.equals(configBusiParamDocumentInfo.getDocumentKindCode()) && Constant.STRING_1.equals(recordInfo.getDocumentRecordStatus()) && !DocumentStatusEnum.CHECK_BACK.getCode().equals(recordInfo.getDocumentApprovalStatus()) && !DocumentStatusEnum.WAIT_TO_SUBMIT.getCode().equals(recordInfo.getDocumentApprovalStatus())) {
                throw new BusinessException("责令改正通知书已制作请勿重复制作！");
            }
        }
        if (ObjectUtil.isEmpty(templateCode)) {
            templateCode = getTemplateCodeByDocumentCatalogCode(request.getDocumentCatalogCode(), request.getCaseId(), null, request.getPartyId());
        }
        Map<String, Object> templateDetail = getTemplateDetail(request.getDocumentCatalogCode(), request.getCaseId(), null, templateCode, request.getPartyId());
        Map<String, Object> objectMap = JSON.parseObject(templateDetail.get("templateFieldConfigs").toString());
        vo.setHtmlContent(templateDetail.get("htmlContent") == null ? "" : templateDetail.get("htmlContent").toString());
        vo.setTemplateConfigMap(objectMap);
        vo.setTemplateCode(templateCode);
        return vo;
    }

    public DocumentCommonFormHtmlVo getDocBaseInfoByDocumentTemplateCode(StageDocCommonHtmlRequest request) {
        DocumentCommonFormHtmlVo vo = new DocumentCommonFormHtmlVo();
        Map<String, Object> templateDetail = getTemplateDetail(request.getDocumentTemplateCode());
        Map<String, Object> objectMap = JSON.parseObject(templateDetail.get("templateFieldConfigs").toString());
        vo.setHtmlContent(templateDetail.get("htmlContent") == null ? "" : templateDetail.get("htmlContent").toString());
        vo.setTemplateConfigMap(objectMap);
        return vo;
    }

    @Override
    public DocumentCommonFormDataVo getCommonDocumentFormData(StageDocCommonHtmlRequest request) {
        DocumentCommonFormDataVo vo = new DocumentCommonFormDataVo();
        // Map<String, Object> templateDetail = getTemplateDetail(request.getDocumentCatalogCode(), request.getCaseId(),null);
        Map<String, Object> resultData = new HashMap<>();
        ConfigBusiParamDocumentInfo configBusiParamDocumentInfo = configBusiParamDocumentInfoService.getDetailByDocumentCatalogCode(request.getDocumentCatalogCode());
        String documentKindCode = configBusiParamDocumentInfo.getDocumentKindCode();
        //查询历史记录
        CaseDocumentRecord recordInfo = null;
        if (DocumentKindEnum.DOC_KIND_DK1BZGZSPB.getCode().equals(documentKindCode)) {
            recordInfo = caseDocumentRecordMapper.selectByPrimaryKey(request.getDocumentId());
        } else {
            recordInfo = caseDocumentRecordService.getCaseDocumentRecord(request.getCaseId(), request.getDocumentCatalogCode(), request.getPartyId());
        }
        String templateCode = request.getDocumentTemplateCode();
        if (ObjectUtil.isNotEmpty(recordInfo) && ObjectUtil.isNotEmpty(recordInfo.getDocumentContent())) {
            String documentContent = "";
            templateCode = recordInfo.getDocumentTemplateCode();

            documentContent = recordInfo.getDocumentContent();
            resultData = JSON.parseObject(documentContent);
            vo.setOperateType(RecordSaveTypeEnum.MOD.getCode());
            //更正公示
            if (DocumentKindEnum.DOC_KIND_DT1SQGZGSSPB.getCode().equals(documentKindCode) &&
                    DocumentStatusEnum.CHECK_END.getCode().equals(recordInfo.getDocumentApprovalStatus())) {
                dealCommonDocumentFormData(request, resultData, templateCode);
                vo.setOperateType(RecordSaveTypeEnum.ADD.getCode());
            }
            //中止申请
            if (CaseStatusChangeTypeEnum.SUSPEND.getDocumentKindCode().equals(documentKindCode)) {
                CaseMainInfoStatusChangeRecord record = caseMainInfoStatusChangeRecordService.getCaseMainInfoStatusChangeRecordByChangeType(request.getCaseId(), CaseStatusChangeTypeEnum.SUSPEND.getCode());
                if (ObjectUtil.isNotEmpty(record)) {
                    if (Constant.STRING_2.equals(record.getStatus())) {
                        dealCommonDocumentFormData(request, resultData, templateCode);
                        vo.setOperateType(RecordSaveTypeEnum.ADD.getCode());
                    } else if (Constant.STRING_1.equals(record.getStatus())) {
                        throw new BusinessException("暂停中请先恢复");
                    } else {
                        documentContent = recordInfo.getDocumentContent();
                        resultData = JSON.parseObject(documentContent);
                        vo.setOperateType(RecordSaveTypeEnum.MOD.getCode());
                    }
                }

            }

        } else {
            //查询是否 有暂存
            CaseTemporaryRecord record = caseTemporaryRecordService.getRecord(request.getCaseId(), request.getDocumentCatalogCode(), request.getPartyId());
            if (record != null) {
                JSONObject json = JSONObject.parseObject(record.getContent());
                vo.setDataMap(json.getJSONObject("dataMap"));
                vo.setOperateType(RecordSaveTypeEnum.TEMP.getCode());
                return vo;
            }

            //初次获取数据
            dealCommonDocumentFormData(request, resultData, templateCode);
            //暂存end
            vo.setOperateType(RecordSaveTypeEnum.ADD.getCode());

        }
        vo.setTemplateCode(templateCode);
        vo.setDataMap(resultData);
        return vo;
    }

    /**
     * 获取通用文书表单数据(根据documentRecordId)
     *
     * @param request 请求
     * @return {@link DocumentCommonFormDataVo }
     */
    @Override
    public DocumentCommonFormDataVo getDocFormDataByDocRecordId(StageDocCommonHtmlRequest request) {
        DocumentCommonFormDataVo vo = new DocumentCommonFormDataVo();
        Map<String, Object> resultData = new HashMap<>();
        //获取配置
        ConfigBusiParamDocumentInfo configBusiParamDocumentInfo = configBusiParamDocumentInfoService.getDetailByDocumentCatalogCode(request.getDocumentCatalogCode());
        String documentKindCode = configBusiParamDocumentInfo.getDocumentKindCode();
        CaseDocumentRecord recordInfo = null;
        if (StrUtil.isNotEmpty(request.getDocumentId())) {
            recordInfo = caseDocumentRecordMapper.selectByPrimaryKey(request.getDocumentId());
        }
        String templateCode = request.getDocumentTemplateCode();
        if (ObjectUtil.isNotEmpty(recordInfo) && ObjectUtil.isNotEmpty(recordInfo.getDocumentContent())) {
            String documentContent = "";
            templateCode = recordInfo.getDocumentTemplateCode();

            documentContent = recordInfo.getDocumentContent();
            resultData = JSON.parseObject(documentContent);
            vo.setOperateType(RecordSaveTypeEnum.MOD.getCode());
            //更正公示
            if (DocumentKindEnum.DOC_KIND_DT1SQGZGSSPB.getCode().equals(documentKindCode) &&
                    DocumentStatusEnum.CHECK_END.getCode().equals(recordInfo.getDocumentApprovalStatus())) {
                dealCommonDocumentFormData(request, resultData, templateCode);
                vo.setOperateType(RecordSaveTypeEnum.ADD.getCode());
            }
            //中止申请
            if (CaseStatusChangeTypeEnum.SUSPEND.getDocumentKindCode().equals(documentKindCode)) {
                CaseMainInfoStatusChangeRecord record = caseMainInfoStatusChangeRecordService.getCaseMainInfoStatusChangeRecordByChangeType(request.getCaseId(), CaseStatusChangeTypeEnum.SUSPEND.getCode());
                if (ObjectUtil.isNotEmpty(record)) {
                    if (Constant.STRING_2.equals(record.getStatus())) {
                        dealCommonDocumentFormData(request, resultData, templateCode);
                        vo.setOperateType(RecordSaveTypeEnum.ADD.getCode());
                    } else if (Constant.STRING_1.equals(record.getStatus())) {
                        throw new BusinessException("暂停中请先恢复");
                    } else {
                        documentContent = recordInfo.getDocumentContent();
                        resultData = JSON.parseObject(documentContent);
                        vo.setOperateType(RecordSaveTypeEnum.MOD.getCode());
                    }
                }
            }
        } else {
            //初次获取数据
            dealCommonDocumentFormData(request, resultData, templateCode);
            //暂存end
            vo.setOperateType(RecordSaveTypeEnum.ADD.getCode());
        }
        vo.setTemplateCode(templateCode);
        vo.setDataMap(resultData);
        return vo;
    }


    private void dealCommonDocumentFormData(StageDocCommonHtmlRequest request, Map<String, Object> resultData, String templateCode) {
        Map<String, Object> templateDetail = getTemplateDetail(request.getDocumentCatalogCode(), request.getCaseId(), null, templateCode, request.getPartyId());
        //根据表名，分组查询所需字段数据，放入一个map中
        Map<String, String> sourceDataMap = new HashMap<>();
        if (ObjectUtil.isNotEmpty(templateDetail.get("sourceFieldInfos"))) {
            Map<String, Object> sourceFieldInfos = JSON.parseObject(templateDetail.get("sourceFieldInfos").toString());
            // 从表中获取数据
            sourceDataMap = getSourceDataMap(sourceFieldInfos, request);
        }
        if (ObjectUtil.isNotEmpty(templateDetail.get("templateFieldConfigs"))) {
            //循环给自动填充的字段赋值
            Map templateFieldConfigs = JSON.parseObject(templateDetail.get("templateFieldConfigs").toString());
            Set<String> templateConfigSet = templateFieldConfigs.keySet();
            for (String configKey : templateConfigSet) {
                String value = "";
                JSONObject paramMap = JSON.parseObject(templateFieldConfigs.get(configKey).toString());
                if (ObjectUtil.isNotEmpty(paramMap.get("isAutoData")) && Constant.WHETHER_STRING_YES.equals(paramMap.get("isAutoData"))) {
                    String dataGenerateRule = paramMap.getString("dataGenerateRule");
                    //自动数据来源，SOURCE_ARTIFICIAL页面填充，SOURCE_SYSTEM系统字段
                    if ("SOURCE_ARTIFICIAL".equals(paramMap.getString("autoDataSource"))) {
                        value = dataGenerateRule;
                    } else if ("SOURCE_SYSTEM".equals(paramMap.getString("autoDataSource"))) {
                        //组装参数结果
                        value = ParseTextUtil.parseText(dataGenerateRule, sourceDataMap);
                        //格式化日期控件
                        if ("3".equals(paramMap.get("controlType"))) {
                            //日期格式 date ，时间time，日期时间datetime  "timeShow":"yyyy年MM月dd日 hh时mm分ss秒"
                            JSONObject dateConfig = paramMap.getJSONObject("controlConfigContent");
                            String pickerType = dateConfig.getString("pickerType");
                            String timeShow = dateConfig.getString("timeShow");
                            value = DateUtil.formatDate(value, timeShow, pickerType);
                        } else if ("SOURCE_SYSTEM_List".equals(paramMap.getString("autoDataSource"))) {

                        }
                    }
                    resultData.put(paramMap.getString("templateFieldEn"), value);
                }
                // 控件类型是签名 获取执法人员签名
                if (ObjectUtil.isNotEmpty(paramMap.getString("controlType"))) {

                }
            }
        }
    }

    /**
     * 根据模板字段配置信息，组装查询所需要的字段，并组装成map格式
     *
     * @param sourceFieldInfos 源字段信息
     * @param request          请求
     * @return {@link Map<String, String> }
     * @author shishengyao
     * @date 2022/02/28
     */
    private Map<String, String> getSourceDataMap(Map<String, Object> sourceFieldInfos, StageDocCommonHtmlRequest request) {
        Map<String, String> sourceDataMap = new HashMap<>();
        Set<String> keySet = sourceFieldInfos.keySet();
        for (String tableName : keySet) {
            try {
                List<String> fieldList = JSONObject.parseArray(sourceFieldInfos.get(tableName).toString(), String.class);
                String fieldSql = StringUtils.join(fieldList, ",");
                String conditionSql = "";
                String whereSql = "case_id=" + "'" + request.getCaseId() + "'";
                if ("case_main_info".equals(tableName)) {
                    conditionSql = " from upcase." + tableName;
                    whereSql = "id=" + "'" + request.getCaseId() + "'";
                } else if ("case_parties_person_info".equals(tableName)
                        || "case_parties_legal_info".equals(tableName)
                        || "case_parties_record".equals(tableName)) {
                    List<String> packFieldList = new ArrayList<>();
                    for (String field : fieldList) {
                        String packField = " string_agg ( " + field + ", '、' order by party_type,create_time  desc ) as " + field;
                        packFieldList.add(packField);
                    }
                    fieldSql = StringUtils.join(packFieldList, ",");
                    if ("case_parties_record".equals(tableName)) {
                        conditionSql = " from upcase." + tableName + " cpr ";
                    } else {
                        conditionSql = " from upcase.case_parties_record cpr  left join " + "upcase." + tableName + "  on cpr.party_id=" + tableName + ".id";
                    }
                    whereSql = "cpr.case_id=" + "'" + request.getCaseId() + "'" + " and cpr.status='1' ";
                    if (!ObjectUtils.isEmpty(request.getPartyId()) && !request.getPartyId().contains(",")) {
                        whereSql = whereSql.concat(" and cpr.party_id = '" + request.getPartyId() + "'");
                    }
                } else if ("case_reason_main_record".equals(tableName)) {
                    List<String> packFieldList = new ArrayList<>();
                    for (String field : fieldList) {
                        String packField = " string_agg ( " + field + ", ',' order by " + field + " ASC) as " + field;
                        packFieldList.add(packField);
                    }
                    fieldSql = StringUtils.join(packFieldList, ",");
                    conditionSql = " from upcase." + tableName;
                    whereSql = "case_id=" + "'" + request.getCaseId() + "'" + "and status='1'";
                } else if ("sys_depart_param".equals(tableName)) {
                    conditionSql = " from upcase." + tableName + " sdp left join upcase.case_main_info  on  sdp.org_code=case_main_info.case_org_code";
                    whereSql = "case_main_info.id=" + "'" + request.getCaseId() + "'" + "and is_deleted='0' and sdp.dept_code=case_main_info.case_dept_code";
                } else if ("upcase.case_survey_people_info".equals(tableName)) {
                    conditionSql = " from " + tableName;
                    whereSql = "case_id=" + "'" + request.getCaseId() + "'" + "and id=" + "'" + request.getSurveyPeopleId() + "'";
                } else {
                    conditionSql = " from upcase." + tableName;

                }
                Map<String, Object> dataMap = new HashMap<>();
                String sqlStr = "select " + fieldSql + conditionSql + " where " + whereSql + " limit 1";
                if (StringUtils.isNotEmpty(conditionSql)) {
                    dataMap = stageDocCommonOperateMapper.getDataMap(sqlStr);
                }
                if ("sys_depart_param".equals(tableName) && ObjectUtils.isEmpty(dataMap)) {
                    conditionSql = " from upcase." + tableName + " sdp left join upcase.case_main_info  on  sdp.org_code=case_main_info.case_org_code";
                    whereSql = "case_main_info.id=" + "'" + request.getCaseId() + "'" + "and is_deleted='0' and (dept_code is null or dept_code='') ";
                    sqlStr = "select " + fieldSql + conditionSql + " where " + whereSql + " limit 1";
                    dataMap = stageDocCommonOperateMapper.getDataMap(sqlStr);
                }
                //组装参数值表
                if (ObjectUtil.isNotEmpty(dataMap)) {
                    for (String field : fieldList) {
                        String value = dataMap.get(field) == null ? "" : dataMap.get(field).toString();
//                 value= DateUtil.formatDateStr(value);
                        sourceDataMap.put(tableName + "." + field, value);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return sourceDataMap;
    }

    private Map<String, Object> objectToMap(Object object) {
        Map<String, Object> dataMap = new HashMap<>();
        Class<?> clazz = object.getClass();
        for (Field field : clazz.getDeclaredFields()) {
            try {
                field.setAccessible(true);
                dataMap.put(field.getName(), field.get(object));
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
        return dataMap;
    }

    /**
     * 从文书管理 获取模板详情
     *
     * @param documentCatalogCode 文件目录的代码
     * @return {@link Map<String, Object> }
     * @author shishengyao
     * @date 2022/02/26
     */
    public Map<String, Object> getTemplateDetail(String documentCatalogCode, String caseId, String templateType, String templateCode, String partyId) {
        //根据文书目录编码获取模板code
        if (ObjectUtil.isEmpty(templateCode)) {
            templateCode = getTemplateCodeByDocumentCatalogCode(documentCatalogCode, caseId, null, partyId);
        }
        Map<String, String> headers = HeaderUtil.headerInfo();

        Map<String, Object> paramsMap = new HashMap<>();
        Map<String, Object> requestMap = new HashMap<>();
        requestMap.put("templateCode", templateCode);
        requestMap.put("templateType", templateType);
        String result = HttpUtil.createPost(url.concat(templateDetail)).addHeaders(headers).body(JSON.toJSONString(requestMap)).contentType("application/json").execute().body();
        if (StringUtils.isNotBlank(result)) {
            JSONObject jsonObject = JSONObject.parseObject(result);
            if ("200".equals(jsonObject.get("code").toString())) {
                JSONObject data = JSON.parseObject(jsonObject.get("data").toString());
                //获取返回的html内容
                paramsMap.put("htmlContent", data.getString("standardFormTemplate"));
                paramsMap.put("templateFieldConfigs", data.getString("templateFieldConfigs"));
                paramsMap.put("sourceFieldInfos", data.getString("sourceFieldInfoMap"));
            } else {
                log.info("调用失败，result:" + result);
            }
        }
        return paramsMap;
    }


    public Map<String, Object> getTemplateDetail(String templateCode) {
        Map<String, String> headers = HeaderUtil.headerInfo();

        Map<String, Object> paramsMap = new HashMap<>();
        Map<String, Object> requestMap = new HashMap<>();
        requestMap.put("templateCode", templateCode);
        requestMap.put("templateType", null);
        String result = HttpUtil.createPost(url.concat(templateDetail)).addHeaders(headers).body(JSON.toJSONString(requestMap)).contentType("application/json").execute().body();
        if (StringUtils.isNotBlank(result)) {
            JSONObject jsonObject = JSONObject.parseObject(result);
            if ("200".equals(jsonObject.get("code").toString())) {
                JSONObject data = JSON.parseObject(jsonObject.get("data").toString());
                //获取返回的html内容
                paramsMap.put("htmlContent", data.getString("standardFormTemplate"));
                paramsMap.put("templateFieldConfigs", data.getString("templateFieldConfigs"));
                paramsMap.put("sourceFieldInfos", data.getString("sourceFieldInfoMap"));
            } else {
                log.info("调用失败，result:" + result);
            }
        }
        return paramsMap;
    }

    /**
     * 获取转换生成pdf并上传到oss的地址
     *
     * @param pdfRequest pdf格式的请求
     * @return {@link String }
     * @author shishengyao
     * @date 2022/02/25
     */
    @Override
    public Map<String, String> getConvertedPdfUrl(FillAndConvertToPdfRequest pdfRequest) {

        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("templateCode", pdfRequest.getTemplateCode());
        paramMap.put("paramMap", pdfRequest.getParamMap());
        paramMap.put("templateType", pdfRequest.getTemplateType());
        paramMap.put("isWatermark", pdfRequest.getIsWatermark());
        paramMap.put("watermarkContent", pdfRequest.getWatermarkContent());
        HttpRequest post = HttpUtil.createPost(url + uploadConvertedPdf);
        post.body(JSONObject.toJSONString(paramMap), "application/json");
        String result = post.execute().body();
//        String result = HttpClientUtil.executeRequest(url + uploadConvertedPdf, "POST", "application/json", paramMap);
        if (StringUtils.isNotBlank(result)) {
            JSONObject jsonObject = JSONObject.parseObject(result);
            if ("200".equals(jsonObject.get("code").toString())) {
                String dataResult = jsonObject.get("data").toString();
                JSONObject data = JSON.parseObject(dataResult);
                Map<String, String> resultMap = new HashMap<>();
                //文书地址
                resultMap.put("fileUrl", data.getString("fileUrl"));
                //生成文书base64
                resultMap.put("fileBase64", data.getString("fileBase64"));
                return resultMap;
            } else {
                throw new BusinessException(jsonObject.getString("message"));
            }
        } else {
            throw new BusinessException("文书生成服务网络异常");
        }
    }

    @Override
    @Transactional(rollbackFor = {Error.class, Exception.class})
    @WorkFlowRollAnnotation
    public Map<String, Object> saveDocInfoAuto(StageDocCommonOperateSaveDto saveDto) {
        String caseId = saveDto.getCaseId();
        UserDTO userDTO = UserUtil.getUserInfo();
        CaseMainInfo caseMainInfo = caseMainInfoMapper.selectByPrimaryKey(caseId);

        String handleType = caseMainInfo.getHandleType();
        String casePartiesReasonType = caseMainInfo.getCasePartiesReasonType();
        String documentCatalogCode = saveDto.getDocumentCatalogCode();
        String partyId = saveDto.getPartyId();
        //查询文书配置信息
        ConfigBusiParamDocumentInfo configBusiParamDocumentInfo = configBusiParamDocumentInfoService.getDetailByDocumentCatalogCode(saveDto.getDocumentCatalogCode());
        String documentKindCode = configBusiParamDocumentInfo.getDocumentKindCode();
        saveDto.setDocumentKindCode(documentKindCode);
        //处理特殊文书
        dealSpecialDocument(saveDto);

        CaseMainInfoVo caseMainInfoVo = new CaseMainInfoVo();
        BeanUtils.copyProperties(caseMainInfo, caseMainInfoVo);
        //获取案件信息
        if (caseMainInfoService.validateCaseIsInNotDealStatus(caseMainInfoVo, null)
                && !caseMainInfoService.validateIsTerminateCaseWhenBreakOff(caseMainInfoVo, null, documentKindCode)) {
            //如果存在行政处罚撤销决定书，可以送达
            CaseDocumentRecordDto documentInfo = caseDocumentRecordService.getCaseDocumentRecordByKindCode(caseId, Constant.STRING_KIND_CODE_XZCFCXJDS);
            if (ObjectUtils.isEmpty(documentInfo)) {
                throw new BusinessException("当前案件状态不允许进行该操作");
            }
        }
        //String isShowPartiesSelector = caseMainInfoService.validateIsShowPartiesSelector(caseMainInfoVo, null);
        if (ObjectUtils.isEmpty(partyId)) {
            String caseFlowCode = caseMainInfo.getCaseFlowCode();
            String caseFlowVersion = caseMainInfo.getCaseFlowVersion();
            if (ObjectUtils.isEmpty(caseFlowCode)) {
                caseFlowCode = "-";
            }
            if (ObjectUtils.isEmpty(caseFlowVersion)) {
                caseFlowVersion = "-";
            }
            List<ConfigWorkFlowDocument> configWorkFlowDocumentList = configWorkFlowDocumentService.getConfigWorkFlowDocumentByWorkFLowAndCatalogCode(caseFlowCode, caseFlowVersion, caseMainInfo.getCaseCurrentLinkCode(), documentCatalogCode);
            if (configWorkFlowDocumentList.size() > 0) {
                if (Constant.STRING_2.equals(configWorkFlowDocumentList.get(0).getRelatedHolderType())
                        && HandleTypeEnum.PART_PUNISH.getCode().equals(handleType)) {
                    throw new BusinessException("多当事人分别处罚时请指定当事人id");
                }
                /*if (YesOrNoEnum.YES.getCode().equals(isShowPartiesSelector) &&
                        !CaseStatusChangeTypeEnum.isCaseChangeDocEnum(documentKindCode)) {
                    throw new BusinessException("多当事人分别处罚时请指定当事人id");
                }
                //多当事人，填写时例外 fixme:后期文书目录编码判断可优化成从数据库读取
                if (PartiesReasonTypeEnum.MULTIPLE_PARTIES.getCode().equals(casePartiesReasonType)
                        && "SDDZQRS6486A".equals(documentCatalogCode)) {
                    throw new BusinessException("多当事人时请指定当事人id");
                }*/
                Map<String, String> map = casePartiesRecordService.getCasePartyIdNameInfo(caseId);
                partyId = map.get("partyId");
            } else if (CaseTypeEnum.SIMPLE_PROCEDURE.getCode().equals(caseMainInfo.getCaseType())) {
                Map<String, String> map = casePartiesRecordService.getCasePartyIdNameInfo(caseId);
                partyId = map.get("partyId");
            }
        }


        Map<String, Object> resultMap = new HashMap<>();
        String documentLinkObjectType = configBusiParamDocumentInfo.getDocumentLinkObjectType();
        //分别处罚与当事人关联的文书
        if (Constant.STRING_2.equals(handleType) && Constant.STRING_2.equals(documentLinkObjectType)) {
            resultMap.put("workSubId", saveDto.getPartyId());
        }
        //重新赋值
        saveDto.setPartyId(partyId);
        int num = 0;
        String documentId = "";
        resultMap.put("success", "true");

        //根据文书目录编码获取模板code
        String templateCode = getTemplateCodeByDocumentCatalogCode(saveDto.getDocumentCatalogCode(), caseId, saveDto.getDataMap(), partyId);
        //处理参数
        saveDto.setDocumentTemplateCode(templateCode);
        Map<String, Object> paramMap = dealDocParamMap(saveDto, templateCode);
        long start = System.currentTimeMillis();
        System.out.println("文书生成开始----------------------------------" + start);
        //文号生成;1.判断文号是否已生成 2.未生成则 判断文号生成配置，审批前生成在此处生成，审批后生成在审批完成后生成
        //外部系统对接时使用对应系统文号
        String documentNumber;
        String caseOrgCode = caseMainInfo.getCaseOrgCode();
        Object dataSource = saveDto.getDataMap().get("DATA_SOURCE");
        if (DocumentKindEnum.DOC_KIND_JYCXCFJDS.getCode().equals(documentKindCode)
                && !ObjectUtils.isEmpty(dataSource) && ApiVisitDataSourceEnum.ZJSXFJDZFXT_MOBILE.getId().equals((String) dataSource)) {
            //获取外部系统文号
            XfjdzfDocumentNumberInfoDto dto = new XfjdzfDocumentNumberInfoDto(caseOrgCode, DocumentKindEnum.DOC_KIND_JYCXCFJDS.getCode());
            documentNumber = xfjdzfInterfaceService.getDocumentNumber(dto);
        } else {
            Map<String, Object> resultDocNumberMap = genDocumentNumber(documentCatalogCode, saveDto, configBusiParamDocumentInfo);
            //documentNumber = resultDocNumberMap.get("documentNumber").toString();
            documentNumber = MapUtils.getString(resultDocNumberMap,"documentNumber","");
        }
        paramMap.put("documentNumber", documentNumber);

        //简易程序处罚决定书文号更新至简易案件详情表
        if (!ObjectUtils.isEmpty(documentNumber) && DocumentKindEnum.DOC_KIND_JYCXCFJDS.getCode().equals(documentKindCode)) {
            CaseMainDetailSimpleInfo caseMainDetailSimpleInfo = caseMainDetailSimpleInfoService.getCaseMainDetailSimpleInfo(caseId);
            caseMainDetailSimpleInfo.setPunishDocumentNumber(documentNumber);
            caseMainDetailSimpleInfoMapper.updateByPrimaryKeySelective(caseMainDetailSimpleInfo);
            Example example = new Example(CaseMainDetailAuxiliaryInfo.class);
            example.createCriteria().andEqualTo("caseId", saveDto.getCaseId());
            List<CaseMainDetailAuxiliaryInfo> caseMainDetailAuxiliaryInfos = caseMainDetailAuxiliaryInfoMapper.selectByExample(example);
            if (!ObjectUtils.isEmpty(caseMainDetailAuxiliaryInfos)) {
                for (CaseMainDetailAuxiliaryInfo caseMainDetailAuxiliaryInfo : caseMainDetailAuxiliaryInfos) {
                    CaseMainDetailAuxiliaryInfo updateCaseMainDetailAuxiliaryInfo = new CaseMainDetailAuxiliaryInfo();
                    updateCaseMainDetailAuxiliaryInfo.setId(caseMainDetailAuxiliaryInfo.getId());
                    updateCaseMainDetailAuxiliaryInfo.setPunishDocumentNumber(documentNumber);
                    caseMainDetailAuxiliaryInfoMapper.updateByPrimaryKeySelective(updateCaseMainDetailAuxiliaryInfo);
                }
            }
            //调用行政行为码赋码接口 同时生成二维码 与 条形码
            try {
                //UserDTO userDTO=UserUtil.getUserInfo();
                String areaCode = userDTO.getAreaCode();
                ActsCodeDto actsCodeDto = new ActsCodeDto();
                actsCodeDto.setCaseId(caseId);
                caseActsCodeInfoService.saveCaseActsCodeInfo(actsCodeDto);
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
        //计算送达期限
        String isSend = configBusiParamDocumentInfo.getIsSend();
        String isApprove = configBusiParamDocumentInfo.getIsApprove();
        LocalDate sentDeadLine = null;
        //需要送达不需要审批的文书计算送达期限
        if (YesOrNoEnum.YES.getCode().equals(isSend)
                && !YesOrNoEnum.YES.getCode().equals(isApprove)) {
            Integer limitDay = configBusiParamDocumentInfo.getSendLimitDay();
            String limitDayType = configBusiParamDocumentInfo.getSendLimitType();
            sentDeadLine = caseDocumentRecordService.calculateSentDeadLine(caseId, documentCatalogCode, limitDay, limitDayType, false);
            if (ObjectUtils.isEmpty(sentDeadLine)) {
                throw new BusinessException("未获取到文书送达期限-caseId:" + caseId + ",documentCatalogCode:" + documentCatalogCode);
            }
        }

        //新增: 简易程序处罚决定书处理逻辑： 自行缴纳的，生成支付二维码；当场收缴的不生成支付二维码
        //处罚决定书时获取缴费二维码
        if (Constant.STRING_KIND_CODE_CFJDS.equals(configBusiParamDocumentInfo.getDocumentKindCode())
                || DocumentKindEnum.DOC_KIND_JYCXCFJDS.getCode().equals(configBusiParamDocumentInfo.getDocumentKindCode())) {
            boolean isCreate = true;
            String caseType = caseMainInfo.getCaseType();
            if (CaseTypeEnum.SIMPLE_PROCEDURE.getCode().equals(caseType)) {
                //简易处罚,查询缴款方式
                CaseMainDetailSimpleInfo simpleInfo = caseMainDetailSimpleInfoService.getCaseMainDetailSimpleInfo(caseId);
                if (ObjectUtils.isEmpty(simpleInfo) || !simpleInfo.getPunishKinds().contains("罚款") || PayWayEnum.ON_SITE.getCode().equals(simpleInfo.getPayWay())) {
                    //当场收缴的、处罚不包括罚款的不生成支付二维码
                    isCreate = false;
                }
                // 暂存时不生成真正二维码
                if (isCreate && CaseStatusEnum.TEMP.getCode().equals(caseMainInfo.getCaseStatus())) {
                    paramMap.put("qrBase64", Constant.INVALID_QR_CODE_URL);
                    paramMap.put("paymentQRCodeContent", "缴款二维码：");
                    isCreate = false;
                }
            }

            if (isCreate) {
                //生成缴款单信息
                String paymentSlipNumber = iCasePaymentMainRecordService.saveCasePaymentMainRecord(caseId, documentCatalogCode, partyId, caseType);
                System.out.println("生成缴款单信息耗时------------------------" + (System.currentTimeMillis() - start));
                if (!ObjectUtils.isEmpty(paymentSlipNumber)) {
                    //获取缴款单二维码信息等
                    Map<String, String> paymentInfo = iPunishDecideService.getPaymentInfo(paymentSlipNumber);
                    System.out.println("获取缴款单二维码信息等耗时------------------------" + (System.currentTimeMillis() - start));
                    //paramMap.put("qrBase64", paymentInfo.get("qrBase64"));
                    //优化成地址
                    paramMap.put("qrBase64", paymentInfo.get("qrUrl"));
                    paramMap.put("XZCFJDS_JKDH", paymentSlipNumber);
                    List payInfoList = new ArrayList();
                    Map<String, String> payInfoMap = new HashMap<>(2);
                    payInfoMap.put("XZCFJDS_JKDH", paymentSlipNumber);
                    //payInfoMap.put("qrBase64", paymentInfo.get("qrBase64"));
                    payInfoMap.put("qrBase64", paymentInfo.get("qrUrl"));
                    payInfoList.add(payInfoMap);
                    paramMap.put("punishKindCheckPayInfo", payInfoList);
                }
            }


        }
        // 处理案件操作变更
        //根据条件添加签章时间
        if ("1".equals(configBusiParamDocumentInfo.getIsDeptSign())) {
            if (("CLOSE-TRIGGER-APPROVAL-PASS".equals(saveDto.getCloseSignal()) && "1".equals(configBusiParamDocumentInfo.getIsApprove())) || !"1".equals(configBusiParamDocumentInfo.getIsApprove())) {
                paramMap.put("sealDate", DateUtils.formatDate(new Date(), "yyyy年M月d日"));
            }
        }
        //案件操作变更
        if (("CLOSE-TRIGGER-APPROVAL-PASS".equals(saveDto.getCloseSignal()) && "1".equals(configBusiParamDocumentInfo.getIsApprove())) || !"1".equals(configBusiParamDocumentInfo.getIsApprove())) {
            if (CaseStatusChangeTypeEnum.isCaseChangeDocEnum(documentKindCode)) {
                CaseStatusUpdateAfterApprovalDto approvalDto = new CaseStatusUpdateAfterApprovalDto();
                approvalDto.setCaseId(saveDto.getCaseId());
                approvalDto.setDocumentKindCode(documentKindCode);
                approvalDto.setCaseOperateType(CaseStatusChangeTypeEnum.getEnumByDocumentKindCode(documentKindCode).getCode());
                caseMainInfoStatusChangeRecordService.updateCaseStatusAfterLastApproval(approvalDto);
                // 处理延期时长
                if (CaseStatusChangeTypeEnum.POSTPONE.getDocumentKindCode().equals(documentKindCode)) {
                    Integer casePostponeDay = Integer.valueOf(saveDto.getDataMap().get(Constant.CASE_POSTPONE_DAY).toString());
                    LocalDateTime postponeDate = caseMainInfo.getCaseTimelimit().plusDays(casePostponeDay);
                    String postponeLimitDate = postponeDate.toLocalDate().format(DateTimeFormatter.ofPattern("yyyy年MM月dd日"));
                    paramMap.put("postponeLimitDate", postponeLimitDate);
                }
            }
        }
        //生成未签章文书
        String areaCode = "";
        try {
            //UserDTO userDTO=UserUtil.getUserInfo();
            areaCode = userDTO.getAreaCode();
        } catch (Exception e) {
            e.printStackTrace();
        }
        FillAndConvertToPdfRequest pdfRequest = new FillAndConvertToPdfRequest();
        List<ConfigBusiParamDocumentInfo> configBusiParamDocumentInfos = configBusiParamDocumentInfoService.getDocumentConfigInfoByDocumentCatalogCode(saveDto.getCaseId(), caseMainInfoVo, saveDto.getDocumentCatalogCode());
        if (!ObjectUtils.isEmpty(configBusiParamDocumentInfos)) {
            ConfigBusiParamDocumentInfo configParamDocumentInfo = configBusiParamDocumentInfos.get(0);
            //行政行为二维码条形码添加
            if (Constant.STRING_1.equals(configParamDocumentInfo.getIsWatermark()) && Constant.STRING_TRUE.equals(isEnable)) {
                //if (Constant.STRING_1.equals(configParamDocumentInfo.getIsWatermark())&&Constant.STRING_TRUE.equals(isEnable)&&TerritoryCodeEnum.ZHZF.getCode().equals(caseMainInfoVo.getCaseTerritoryCode())) {
                boolean isWatermak = true;
                //立案审批表最后一次审批添加水印
                if (DocumentKindEnum.DOC_KIND_LASPB.getCode().equals(documentKindCode) && !"CLOSE-TRIGGER-APPROVAL-PASS".equals(saveDto.getCloseSignal())) {
                    isWatermak = false;
                }
                if (isWatermak) {
                    HashMap<String, Object> dataMap = saveDto.getDataMap();
                    dataMap.put("qrCodeUrl", caseMainInfoVo.getCaseQrCodeUrl());
                    dataMap.put("barCodeUrl", caseMainInfoVo.getCaseBarCodeUrl());
                    saveDto.setDataMap(dataMap);
                    pdfRequest.setIsWatermark(Constant.STRING_1);
                    pdfRequest.setWatermarkContent(caseMainInfoVo.getCaseActsCode());
                }
            }
        }
        pdfRequest.setTemplateCode(templateCode);
        pdfRequest.setParamMap(saveDto.getDataMap());
        //判断文书模板类型是否为窄幅
        if (DocumentTemplateTypeEnum.NARROW_TEMPLATE.getCode().equals(saveDto.getDocumentTemplateType())) {
            pdfRequest.setTemplateType(DocumentTemplateKindEnum.NARROW_TEMPLATE.getCode());
        }
        //简易处罚决定书设置模板类型为窄幅
        if (DocumentKindEnum.DOC_KIND_JYCXCFJDS.getCode().equals(documentKindCode)) {
            pdfRequest.setTemplateType(DocumentTemplateKindEnum.NARROW_TEMPLATE.getCode());
        }
        Map<String, String> pdfUrl = getConvertedPdfUrl(pdfRequest);
        System.out.println("生成未签章文书耗时------------------------" + (System.currentTimeMillis() - start));
        if (ObjectUtil.isEmpty(pdfUrl)) {
            resultMap.put("success", "false");
            resultMap.put("msg", "文书生成失败！");
            return resultMap;
        }
        //判断是否需要签章
        String pdfSealUrl = "";
        String isGetBlankDoc = saveDto.getIsGetBlankDoc();
        String noSealPdfUrl = pdfUrl.get("fileUrl");
        if ("1".equals(configBusiParamDocumentInfo.getIsDeptSign()) && !YesOrNoEnum.YES.getCode().equals(isGetBlankDoc)) {
            //文书签章 1.非审批文书签章 2.审批通过文书签章
            if (("CLOSE-TRIGGER-APPROVAL-PASS".equals(saveDto.getCloseSignal()) && "1".equals(configBusiParamDocumentInfo.getIsApprove())) || !"1".equals(configBusiParamDocumentInfo.getIsApprove())) {
                FileSealInfoQueryDto queryDto = new FileSealInfoQueryDto();
                String uniscid = getUniscidByOrgCode(caseMainInfo.getCaseOrgCode(), caseMainInfo.getCaseDeptCode());
                queryDto.setFileBase64(pdfUrl.get("fileBase64"));
                queryDto.setUniscid(uniscid);
                queryDto.setDeptCode(caseMainInfo.getCaseDeptCode());
                pdfSealUrl = dealFileSealAuto(queryDto);
                if (log.isDebugEnabled()) {
                    log.debug("签章耗时------------------------" + (System.currentTimeMillis() - start));
                }
                if (StringUtils.isBlank(pdfSealUrl)) {
                    resultMap.put("success", "false");
                    resultMap.put("msg", "文书签章失败！");
                    return resultMap;
                }
                Map<String, Object> operateMap = operateCaseDocumentRecord(saveDto.getCaseAssistId(), saveDto.getDocumentCatalogCode(), caseMainInfo, pdfUrl.get("fileUrl"), documentNumber, paramMap, pdfSealUrl, sentDeadLine, saveDto.getIsMultipleDoc(), saveDto.getBelongDocumentId(), partyId, saveDto.getDocumentTemplateType(), saveDto.getZlbCaseDocumentRecordDto(), saveDto.getIsEditFile(), saveDto.getDocId(), templateCode);
                num = MapUtils.getIntValue(operateMap, "num", 0);
                documentId = MapUtils.getString(operateMap, "documentId", "");
            }
            if (!"CLOSE-TRIGGER-APPROVAL-PASS".equals(saveDto.getCloseSignal()) && "1".equals(configBusiParamDocumentInfo.getIsApprove())) {
                //num = operateCaseDocumentRecord(saveDto.getDocumentCatalogCode(), caseMainInfo, pdfUrl.get("fileUrl"), documentNumber, paramMap, pdfSealUrl, sentDeadLine);

                //从签字捺印过来，原先签章文件是非空的，要保留
                CaseDocumentRecord oriRecord = caseDocumentRecordService.getCaseDocumentRecord(caseId, documentCatalogCode, partyId);
                if (!ObjectUtils.isEmpty(oriRecord) && !ObjectUtils.isEmpty(oriRecord.getDocumentUrlAfterSeal())) {
                    pdfSealUrl = oriRecord.getDocumentUrlAfterSeal();
                }
                //num = operateCaseDocumentRecord(saveDto.getDocumentCatalogCode(), caseMainInfo, pdfUrl.get("fileUrl"), documentNumber, paramMap, pdfSealUrl, sentDeadLine);
                Map<String, Object> operateMap = operateCaseDocumentRecord(saveDto.getCaseAssistId(), saveDto.getDocumentCatalogCode(), caseMainInfo, pdfUrl.get("fileUrl"), documentNumber, paramMap, pdfSealUrl, sentDeadLine, saveDto.getIsMultipleDoc(), saveDto.getBelongDocumentId(), partyId, saveDto.getDocumentTemplateType(), saveDto.getZlbCaseDocumentRecordDto(), saveDto.getIsEditFile(), saveDto.getDocId(), templateCode);
                num = MapUtils.getIntValue(operateMap, "num", 0);
                documentId = MapUtils.getString(operateMap, "documentId", "");
            }
            if ("CLOSE-TRIGGER-APPROVAL-PASS".equals(saveDto.getCloseSignal()) && "1".equals(configBusiParamDocumentInfo.getIsApprove())) {
                //审批通过，关联文书签章
                //查询关联文书
                String relationDocumentCatalogCode = configBusiParamDocumentInfo.getRelationDocumentCatalogCode();
                if (StringUtils.isNotBlank(relationDocumentCatalogCode)) {
                    String[] relationDocumentCatalogCodeArr = relationDocumentCatalogCode.split(",");
                    for (String relationDocumentCatalogCodeStr : relationDocumentCatalogCodeArr) {
                        log.info("caseId:{},relationDocumentCatalogCodeStr:{},partyId:{}", caseId, relationDocumentCatalogCodeArr, partyId);
                        CaseDocumentRecord caseDocumentRecord = caseDocumentRecordService.getCaseDocumentRecord(caseId, relationDocumentCatalogCodeStr, partyId);
                        if (caseDocumentRecord != null) {
                            String documentContent = caseDocumentRecord.getDocumentContent();
                            JSONObject jsonObject = JSON.parseObject(documentContent);
                            HashMap<String, Object> jsonMap = new HashMap<>(16);
                            for (Map.Entry<String, Object> entry : jsonObject.entrySet()) {
                                jsonMap.put(entry.getKey(), entry.getValue());
                            }
                            jsonMap.put("sealDate", DateUtils.formatDate(new Date(), "yyyy年M月d日"));
                            //审批人签名信息添加
                            HashMap<String, Object> dataMap1 = saveDto.getDataMap();
                            for (OpinionType ot : OpinionType.values()) {
                                Object o = dataMap1.get(ot.getAuditUserIdCode());
                                if (!ObjectUtils.isEmpty(o)) {
                                    jsonMap.put(ot.getAuditUserIdCode(), o.toString());
                                    jsonMap.put(ot.getAuditTimeCode(), DateUtils.formatDate(new Date(), "yyyy年M月d日"));
                                }
                            }

                            //生成文号
                            ConfigBusiParamDocumentInfo relateConfigBusiParamDocumentInfo = configBusiParamDocumentInfoService.getDetailByDocumentCatalogCode(relationDocumentCatalogCodeStr);
                            Map<String, Object> resultDocNumberMap = genDocumentNumber(relationDocumentCatalogCodeStr, saveDto, relateConfigBusiParamDocumentInfo);
                            String relateDocumentNumber = resultDocNumberMap.get("documentNumber").toString();
                            ConfigBusiParamDocumentInfo configInfo = configBusiParamDocumentInfoService.getDetailByDocumentCatalogCode(relationDocumentCatalogCodeStr);
                            String relatedDocumentKindCode = configInfo.getDocumentKindCode();

                            //计算送达期限(关联文书)
                            String isSendOfRelation = relateConfigBusiParamDocumentInfo.getIsSend();
                            String isApproveOfRelation = relateConfigBusiParamDocumentInfo.getIsApprove();
                            LocalDate sentDeadLineOfRelation = null;
                            //关联文书需要送达且需要审批重新生成送达截止时间
                            if (YesOrNoEnum.YES.getCode().equals(isSendOfRelation)
                                    && YesOrNoEnum.YES.getCode().equals(isApproveOfRelation)) {
                                Integer limitDay = relateConfigBusiParamDocumentInfo.getSendLimitDay();
                                String limitDayType = relateConfigBusiParamDocumentInfo.getSendLimitType();
                                sentDeadLineOfRelation = caseDocumentRecordService.calculateSentDeadLine(caseId, relationDocumentCatalogCodeStr, limitDay, limitDayType, false);
                                if (ObjectUtils.isEmpty(sentDeadLineOfRelation)) {
                                    throw new BusinessException("未获取到文书送达期限-caseId:" + caseId + ",documentCatalogCode:" + relationDocumentCatalogCodeStr);
                                }
                            }

                            //处罚决定书文号更新至案件详情表
                            if (!ObjectUtils.isEmpty(relateDocumentNumber) && (Constant.STRING_KIND_CODE_CFJDS.equals(relatedDocumentKindCode) || Constant.STRING_KIND_CODE_BYCFJDS.equals(relatedDocumentKindCode))) {
                                //判断是否多当事人分别处罚
                                if (caseMainInfoService.checkCaseIsPartiesPartPunish(caseId, null)) {
                                    CaseMainDetailAuxiliaryInfo caseMainDetailAuxiliaryInfo = new CaseMainDetailAuxiliaryInfo();
                                    caseMainDetailAuxiliaryInfo.setCaseId(caseId);
                                    caseMainDetailAuxiliaryInfo.setPartyId(partyId);
                                    caseMainDetailAuxiliaryInfo.setPunishDocumentNumber(relateDocumentNumber);
                                    caseMainDetailAuxiliaryInfoService.updateSpecialParam(caseMainDetailAuxiliaryInfo);
                                } else {
                                    CaseMainDetailInfo caseMainDetailInfo = new CaseMainDetailInfo();
                                    caseMainDetailInfo.setCaseId(caseId);
                                    caseMainDetailInfo.setPunishDocumentNumber(relateDocumentNumber);
                                    caseMainDetailInfoMapper.updateByPrimaryKeySelective(caseMainDetailInfo);
                                    try {
                                        //单当事人单案由 更新补充表数据
                                        CaseMainDetailAuxiliaryInfo caseMainDetailAuxiliaryInfo = new CaseMainDetailAuxiliaryInfo();
                                        caseMainDetailAuxiliaryInfo.setCaseId(caseId);
                                        caseMainDetailAuxiliaryInfo.setPunishDocumentNumber(relateDocumentNumber);
                                        caseMainDetailAuxiliaryInfoService.editSpecialParamSingle(caseMainDetailAuxiliaryInfo);
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                    }

                                }
                            }
                            jsonMap.put("documentNumber", relateDocumentNumber);
                            String relateTemplateCode = getTemplateCodeByDocumentCatalogCode(relationDocumentCatalogCodeStr, caseId, jsonMap, saveDto.getPartyId());
                            FillAndConvertToPdfRequest relatePdfRequest = new FillAndConvertToPdfRequest();
                            //行政行为二维码条形码添加
                            if (Constant.STRING_1.equals(relateConfigBusiParamDocumentInfo.getIsWatermark()) && Constant.STRING_TRUE.equals(isEnable)) {
                                //if (Constant.STRING_1.equals(relateConfigBusiParamDocumentInfo.getIsWatermark())&&Constant.STRING_TRUE.equals(isEnable)&&TerritoryCodeEnum.ZHZF.getCode().equals(caseMainInfoVo.getCaseTerritoryCode())) {
                                boolean isWatermak = true;
                                //立案审批表最后一次审批添加水印
                                if (DocumentKindEnum.DOC_KIND_LASPB.getCode().equals(documentKindCode) && !"CLOSE-TRIGGER-APPROVAL-PASS".equals(saveDto.getCloseSignal())) {
                                    isWatermak = false;
                                }
                                if (isWatermak) {
                                    HashMap<String, Object> dataMap = saveDto.getDataMap();
                                    jsonMap.put("qrCodeUrl", caseMainInfoVo.getCaseQrCodeUrl());
                                    jsonMap.put("barCodeUrl", caseMainInfoVo.getCaseBarCodeUrl());
                                    relatePdfRequest.setIsWatermark(Constant.STRING_1);
                                    relatePdfRequest.setWatermarkContent(caseMainInfoVo.getCaseActsCode());
                                }
                            }
                            relatePdfRequest.setTemplateCode(relateTemplateCode);
                            relatePdfRequest.setParamMap(jsonMap);
                            Map<String, String> relatePdfUrl = getConvertedPdfUrl(relatePdfRequest);
                            System.out.println("关联文书生成耗时------------------------" + (System.currentTimeMillis() - start));
                            // String fileBase64=;
                            String uniscid = getUniscidByOrgCode(caseMainInfo.getCaseOrgCode(), caseMainInfo.getCaseDeptCode());
                            FileSealInfoQueryDto queryDto = new FileSealInfoQueryDto();
                            queryDto.setFileBase64(relatePdfUrl.get("fileBase64"));
                            queryDto.setUniscid(uniscid);
                            queryDto.setDeptCode(caseMainInfo.getCaseDeptCode());
                            String relatePdfSealUrl = dealFileSealAuto(queryDto);
                            if (log.isDebugEnabled()) {
                                log.debug("关联文书签章耗时------------------------" + (System.currentTimeMillis() - start));
                            }
                            //operateCaseDocumentRecord(relationDocumentCatalogCodeStr, caseMainInfo, relatePdfUrl.get("fileUrl"), relateDocumentNumber, paramMap, relatePdfSealUrl, sentDeadLine);
                            operateCaseDocumentRecord(saveDto.getCaseAssistId(), relationDocumentCatalogCodeStr, caseMainInfo, relatePdfUrl.get("fileUrl"), relateDocumentNumber, jsonMap, relatePdfSealUrl, sentDeadLineOfRelation, saveDto.getIsMultipleDoc(), saveDto.getBelongDocumentId(), partyId, saveDto.getDocumentTemplateType(), saveDto.getZlbCaseDocumentRecordDto(), "", "", templateCode);
                            if (StringUtils.isBlank(pdfSealUrl)) {
                                resultMap.put("success", "false");
                                resultMap.put("msg", "文书签章失败！");
                                return resultMap;
                            }
                        }
                    }
                }
            }
        } else {
            //num = operateCaseDocumentRecord(saveDto.getDocumentCatalogCode(), caseMainInfo, pdfUrl.get("fileUrl"), documentNumber, paramMap, pdfSealUrl, sentDeadLine);
            Map<String, Object> operateMap = operateCaseDocumentRecord(saveDto.getCaseAssistId(), saveDto.getDocumentCatalogCode(), caseMainInfo, pdfUrl.get("fileUrl"), documentNumber, paramMap, pdfSealUrl, sentDeadLine, saveDto.getIsMultipleDoc(), saveDto.getBelongDocumentId(), partyId, saveDto.getDocumentTemplateType(), saveDto.getZlbCaseDocumentRecordDto(), saveDto.getIsEditFile(), saveDto.getDocId(), templateCode);
            num = MapUtils.getIntValue(operateMap, "num", 0);
            documentId = MapUtils.getString(operateMap, "documentId", "");
        }
        if (("CLOSE-TRIGGER-APPROVAL-PASS".equals(saveDto.getCloseSignal()) && "1".equals(configBusiParamDocumentInfo.getIsApprove())) || !"1".equals(configBusiParamDocumentInfo.getIsApprove())) {
            //处罚决定撤销时相关流程更新
            CasePunishDecisionRevokeRecordVo vo = casePunishDecisionRevokeRecordService.getCasePunishDecisionRevokeRecordBasicInfo(caseId);
            if (!ObjectUtils.isEmpty(vo)) {
                String revokeReasonCode = vo.getRevokeReasonCode();
                if (PunishDecisionRevokeReasonEnum.FYSSHCX.getCode().equals(revokeReasonCode)) {
                    //没有行政处罚撤销决定书
                    if (Constant.STRING_KIND_CODE_XZCFCXSPB.equals(documentKindCode)) {
                        casePunishDecisionRevokeRecordService.dealAfterPunishRevoke(caseId, vo.getDealAfterRevokeTypeCode());
                    }
                }
            }
            //公示变更
            if (CasePublicityModifyEnum.isLegalEnumCodeByKindCode(documentKindCode)) {
                casePublicityModifyRecordService.dealPublicityModifyAfterFinishApproval(caseId, documentKindCode, documentId);
            }
        }
        //操作文书记录表 判断文书记录是否存在，存在则添加历史表，然后更新数据
        if (num < 1) {
            resultMap.put("success", "false");
            resultMap.put("msg", "保存失败！");
            return resultMap;
        }
        if (CaseStatusEnum.PUNISH_NO_REGISTER.getCode().equals(caseMainInfoVo.getCaseStatus()) && ApiVisitDataSourceEnum.PUNISH_AY.getCode().equals(caseMainInfoVo.getDataSource())) {
            resultMap.put("success", "true");
            resultMap.put("msg", "生成成功！");
            return resultMap;
        }
        //送达回证特殊处理
        String receiptDocUrl = pdfSealUrl;
        if (YesOrNoEnum.YES.getCode().equals(isGetBlankDoc)) {
            //空白送达回证无需签章
            receiptDocUrl = noSealPdfUrl;
        } else {
            receiptDocUrl = pdfSealUrl;
        }
        updateDocumentRecordInfoAfterSentReceiptPrint(documentCatalogCode, pdfUrl, receiptDocUrl, caseId, isGetBlankDoc, partyId);
        System.out.println("送达回证特殊处理耗时------------------------" + (System.currentTimeMillis() - start));
        //非诉执行立案申请
        nonLitigationExecute(saveDto);
        //案件状态变更操作
        updateCaseStatusChange(saveDto, documentId, configBusiParamDocumentInfo);
        //若需要更新则根据配置更新相关数据
        if (!YesOrNoEnum.NO.getCode().equals(saveDto.getIsUpdateRelationTable())) {
            operateBusiTableByDocumentCatalogCode(saveDto);
        }
        String closeSignal = saveDto.getCloseSignal();
        if (StringUtils.isBlank(closeSignal)) {
            closeSignal = "CLOSE-TRIGGER-DOCCREATE";
        }
        resultMap.put("closeSignal", closeSignal);
        //简易程序案件流程无需滚动,不设置workId
        //非简易程序时设置workId
        if (!CaseTypeEnum.SIMPLE_PROCEDURE.getCode().equals(caseMainInfo.getCaseType())) {
            resultMap.put("workId", caseId);
        }
        resultMap.put("documentId", documentId);
        resultMap.put("documentCatalogCode", documentCatalogCode);
        if (StringUtils.isNotBlank(saveDto.getCaseAssistId())) {
            resultMap.put("workAssistId", saveDto.getCaseAssistId());
        }
        // 证据库案件信息同步对接
        try {
            String la = "LASPB";
            if (saveDto.getDocumentCatalogCode().contains(la) && StringUtils.isNotBlank(documentNumber)) {
                //调用行政行为码赋码接口 同时生成二维码 与 条形码
                //caseActsCodeInfoService.saveCaseActsCodeInfo(caseMainInfoVo);
                // 换为证据库新API
                if (SpringContextUtil.checkIsPrdProfile() || SpringContextUtil.checkIsDevProfile()) {
                    evidenceInventoryService.saveEvent(caseId, documentNumber);
                }
            }
        } catch (Exception e) {
            log.info("证据库立案对接失败:{}", e.getMessage());
        }
        return resultMap;
    }

    /**
     * 文件签章并上传到oss
     *
     * @param queryDto 查询dto
     * @return {@link Map<String, String> }
     * @author shishengyao
     * @date 2022/03/07
     */
    @Override
    public String dealFileSeal(FileSealInfoQueryDto queryDto) {
        queryDto.setFileType("pdf");
        queryDto.setFileTransferForm("1");
        queryDto.setFileBase64(queryDto.getFileBase64());
        queryDto.setAddSignTime(false);
        queryDto.setSealCode("");
        queryDto.setKey("签章处");
        queryDto.setSignType(4);
        queryDto.setSealCode("12");
        queryDto.setPosX(0);
        queryDto.setPosY(0);
        //签章
        Map<String, Object> fileAfterSeal = fileSealProvinceUnifiedService.getFileAfterSeal(queryDto);
        if (ObjectUtil.isNotEmpty(fileAfterSeal.get("errorMsg"))) {
            log.info("warn fileSealService,result:{}", fileAfterSeal.get("errorMsg"));
            throw new BusinessException(fileAfterSeal.get("errorMsg").toString());
        }
        //获取pdf页码若2张以上，加盖骑缝章
        try {
            byte[] fileBytes = (byte[]) fileAfterSeal.get("fileBytes");
            InputStream ins = new ByteArrayInputStream(fileBytes);
            PdfReader pdfReader = new PdfReader(ins);
            int pages = pdfReader.getNumberOfPages();
            if (pages > 1) {
                queryDto.setFileType("pdf");
                queryDto.setFileTransferForm("1");
                String base64 = Base64.encodeBase64String(fileBytes);
                queryDto.setFileBase64(base64);
                queryDto.setKey("");
                queryDto.setSealCode("21");
                queryDto.setSignType(3);
                queryDto.setPosX(100);
                queryDto.setPosY(450);
                queryDto.setPosPage("1-" + pages);
                fileAfterSeal = fileSealProvinceUnifiedService.getFileAfterSeal(queryDto);
                if (ObjectUtil.isNotEmpty(fileAfterSeal.get("errorMsg"))) {
                    log.info("warn fileSealService,result:{}", fileAfterSeal.get("errorMsg"));
                    throw new BusinessException(fileAfterSeal.get("errorMsg").toString());
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
            throw new BusinessException("系统异常:" + e.getMessage());
        }

        //上传签章后的文件到oss
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("fileBytes", fileAfterSeal.get("fileBytes"));
        jsonObject.put("fileType", "pdf");
        jsonObject.put("fileName", "");
        JSONObject parseObject = JSON.parseObject(HttpUtil.post(url + uploadBase64File, jsonObject.toString()));
        String cd = "code";
        int th = 200;
        if (parseObject.getInteger(cd) == th) {
            String url = parseObject.getJSONObject("data").getString("ossUrl");
            log.info("签章后地址：{}", url);
            return url;
        } else {
            log.info("warn receive sign file upload oss fail,result:{}", parseObject.toString());
            throw new BusinessException("签章后上传文件失败：" + jsonObject.getString("message"));
        }
    }

    public String dealFileSealAuto(FileSealInfoQueryDto queryDto) {
        queryDto.setFileType("pdf");
        queryDto.setFileTransferForm("1");
        queryDto.setFileBase64(queryDto.getFileBase64());
        queryDto.setAddSignTime(false);
        queryDto.setSealCode("");
        queryDto.setKey("签章处");
        queryDto.setSignType(4);
        queryDto.setSealCode("12");
        queryDto.setPosX(0);
        queryDto.setPosY(0);
        //签章
        Map<String, Object> fileAfterSeal = fileSealProvinceUnifiedService.getFileAfterSealAuto(queryDto);
        if (ObjectUtil.isNotEmpty(fileAfterSeal.get("errorMsg"))) {
            log.info("warn fileSealService,result:{}", fileAfterSeal.get("errorMsg"));
            throw new BusinessException(fileAfterSeal.get("errorMsg").toString());
        }
        //获取pdf页码若2张以上，加盖骑缝章
        try {
            byte[] fileBytes = (byte[]) fileAfterSeal.get("fileBytes");
            InputStream ins = new ByteArrayInputStream(fileBytes);
            PdfReader pdfReader = new PdfReader(ins);
            int pages = pdfReader.getNumberOfPages();
            if (pages > 1) {
                queryDto.setFileType("pdf");
                queryDto.setFileTransferForm("1");
                String base64 = Base64.encodeBase64String(fileBytes);
                queryDto.setFileBase64(base64);
                queryDto.setKey("");
                queryDto.setSealCode("21");
                queryDto.setSignType(3);
                queryDto.setPosX(100);
                queryDto.setPosY(450);
                queryDto.setPosPage("1-" + pages);
                fileAfterSeal = fileSealProvinceUnifiedService.getFileAfterSeal(queryDto);
                if (ObjectUtil.isNotEmpty(fileAfterSeal.get("errorMsg"))) {
                    log.info("warn fileSealService,result:{}", fileAfterSeal.get("errorMsg"));
                    throw new BusinessException(fileAfterSeal.get("errorMsg").toString());
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
            throw new BusinessException("系统异常:" + e.getMessage());
        }

        //上传签章后的文件到oss
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("fileBytes", fileAfterSeal.get("fileBytes"));
        jsonObject.put("fileType", "pdf");
        jsonObject.put("fileName", "");
        JSONObject parseObject = JSON.parseObject(HttpUtil.post(url + uploadBase64File, jsonObject.toString()));
        String cd = "code";
        int th = 200;
        if (parseObject.getInteger(cd) == th) {
            String url = parseObject.getJSONObject("data").getString("ossUrl");
            log.info("签章后地址：{}", url);
            return url;
        } else {
            log.info("warn receive sign file upload oss fail,result:{}", parseObject.toString());
            throw new BusinessException("签章后上传文件失败：" + jsonObject.getString("message"));
        }

    }

    /**
     * 描述：处理文书模板填充参数
     *
     * @param saveDto 保存dto
     * @return {@link Map<String, Object> }
     * @author shishengyao
     * @date 2022/03/10
     */
    private Map<String, Object> dealDocParamMap(StageDocCommonOperateSaveDto saveDto, String templateCode) {
        // 送达地址确认书校验参数
        if (DocumentKindEnum.DOC_KIND_SDDZQRS.getCode().equals(saveDto.getDocumentKindCode())) {
            HashMap<String, Object> dataMap = saveDto.getDataMap();
            if (ObjectUtil.isNotEmpty(dataMap.get("SDDZQRS_SJHM"))) {
                if (!BaseUtil.validatePhoneNumber(dataMap.get("SDDZQRS_SJHM").toString())) {
                    throw new BusinessException("送达地址确认书手机号不正确");
                }
            }
            // 自然资源条线送达地址确认书特殊处理，是否电子送达
            if ("DT2SDDZQRS000000001".equals(templateCode)) {
                if (ObjectUtil.isNotEmpty(dataMap.get("SDDZQRS_IS_ELECSENT"))) {
                    String isElecSent = dataMap.get("SDDZQRS_IS_ELECSENT").toString();
                    if (YesOrNoEnum.YES.getDes().equals(isElecSent)) {
                        if (ObjectUtil.isEmpty(dataMap.get("SDDZQRS_SJHM"))
                                & ObjectUtil.isEmpty(dataMap.get("SDDZQRS_CZ"))
                                & ObjectUtil.isEmpty(dataMap.get("SDDZQRS_DZYX"))) {
                            throw new BusinessException("请选择电子送达方式");
                        }
                    } else {
                        dataMap.put("SDDZQRS_SJHM", "");
                        dataMap.put("SDDZQRS_CZ", "");
                        dataMap.put("SDDZQRS_DZYX", "");
                    }
                }
            } else {
                zlbCaseDocumentRecordDto zlbCaseDocumentRecordDto = saveDto.getZlbCaseDocumentRecordDto();
                if (ObjectUtils.isEmpty(zlbCaseDocumentRecordDto)) {
                    if (ObjectUtil.isEmpty(dataMap.get("SDDZQRS_SJHM"))
                            & ObjectUtil.isEmpty(dataMap.get("SDDZQRS_DZ"))
                            & ObjectUtil.isEmpty(dataMap.get("SDDZQRS_DSDZ"))
                            & ObjectUtil.isEmpty(dataMap.get("SDDZQRS_QTDZ"))
                            & ObjectUtil.isEmpty(dataMap.get("SDDZQRS_QTLXFS"))) {
                        throw new BusinessException("送达地址、代收人送达地址、其他电子送达地址、其他联系方式必填一个");
                    }
                }
            }
        }
        //农业农村责令改正通知书参数校验
        if ("DC2A0283300ZLGZTZS000000001".equals(saveDto.getDocumentCatalogCode())) {
            Map<String, Object> dataMap = saveDto.getDataMap();
            boolean fx1 = MapUtils.getBoolean(dataMap, "FX1");
            boolean fx2 = MapUtils.getBoolean(dataMap, "FX2");
            if (!fx1 && !fx2) {
                throw new BusinessException("改正期限未勾选");
            }

            if (fx2) {
                String gzrq = MapUtils.getString(dataMap, "ZLGZTZS_GZRQ", "");
                if (ObjectUtils.isEmpty(gzrq)) {
                    throw new BusinessException("改正时间未选择");
                }
            }
        }
        //农业农村结案报告参数校验
        if ("DC2A0283300JABG000000000001".equals(saveDto.getDocumentCatalogCode())) {
            Map<String, Object> dataMap = saveDto.getDataMap();
            boolean xz7 = MapUtils.getBoolean(dataMap, "XZ7");
            String qt = MapUtils.getString(dataMap, "QT", "");
            if (xz7 && ObjectUtils.isEmpty(qt)) {
                throw new BusinessException("结案情况为其他时，说明不允许为空");
            }

            boolean zxfsxz3 = MapUtils.getBoolean(dataMap, "ZXFSXZ3");
            String qtzxfs = MapUtils.getString(dataMap, "QTZXFS", "");
            if (zxfsxz3 && ObjectUtils.isEmpty(qtzxfs)) {
                throw new BusinessException("执行方式为其他时，说明不允许为空");
            }
        }
        Map<String, Object> paramMap = saveDto.getDataMap();
        if (ObjectUtil.isEmpty(paramMap.get("mainHandleSignPic")) ||
                ObjectUtil.isEmpty("mainHandleSignPic")) {
            Map<String, Object> templateDetail = getTemplateDetail(saveDto.getDocumentCatalogCode(), saveDto.getCaseId(), DocumentTemplateTypeEnum.getMappingCodeByCode(saveDto.getDocumentTemplateType()), saveDto.getDocumentTemplateCode(), saveDto.getPartyId());
            //循环给自动填充的字段赋值
            Map templateFieldConfigs = JSON.parseObject(templateDetail.get("templateFieldConfigs").toString());
            //主办人、承办人签名
            if (ObjectUtil.isNotEmpty(templateFieldConfigs.get("mainHandleSignPic")) ||
                    ObjectUtil.isNotEmpty(templateFieldConfigs.get("assistHandleSignPic"))) {
                List<CaseHandlePersonRecord> personList = caseHandlePersonRecordService.getCaseHandlePersonRecordList(saveDto.getCaseId());
                personList.forEach(e -> {
                    if (HandlePersonTypeEnum.MAIN.getCode().equals(e.getHandlePersonType()) && ObjectUtil.isNotEmpty(templateFieldConfigs.get("mainHandleSignPic"))) {
                        paramMap.put("mainHandleSignPic", e.getHandleSignPic());
                        paramMap.put("mainLawEnforcementCert", e.getLawEnforcementCert());
                    } else if (HandlePersonTypeEnum.ASSIST.getCode().equals(e.getHandlePersonType()) && ObjectUtil.isNotEmpty(templateFieldConfigs.get("assistHandleSignPic"))) {
                        paramMap.put("assistHandleSignPic", e.getHandleSignPic());
                        paramMap.put("assistLawEnforcementCert", e.getLawEnforcementCert());
                    }
                });
            }
        }
        return paramMap;
    }

    /**
     * 描述：【V1.0.0】文书文号生成-主
     *
     * @author tianrunjia
     * @date 2022-02-23
     */
    //@WorkFlowRollAnnotation
    @Override
    public Map<String,Object> getDocumentNumber(String caseId, String documentCatalogCode, String partyId) {
        Map<String,Object> resultMap = new HashMap<>();
        //“X机构”处填写制作法律文书的办案单位文号； X机构（ ）字〔 〕第 号
        //双执法主体切换
        /*List<CaseHandlePersonRecordVo> caseHandlePersonRecordVoList = caseHandlePersonRecordService.getCaseHandlePersonRecordListByCaseId(caseId);
        String handleDeptCode = caseHandlePersonRecordVoList.get(0).getHandleOrgCode();*/
        //String docDeptShort = configBusiParamDeptService.getConfigBusiParamDeptDetailByDeptCode(handleDeptCode).getDocumentDeptShort();
        CaseMainInfo caseMainInfo = caseMainInfoMapper.selectByPrimaryKey(caseId);
        //  SysDepartParam sysDepartParam = sysDepartParamService.getSysDepartParamByOrgCode(caseMainInfo.getCaseOrgCode());
        //   String docDeptShort = sysDepartParam.getOrgShortName();
        //获取委托执法，案件事项
        CaseReasonMainRecord entrustReasonRecord = getEntrustCaseReasonIfExists(caseId, caseMainInfo);
        LineTerritoryInfoVo lineTerritoryInfoVo = Objects.nonNull(entrustReasonRecord) ?
                sysDepartParamService.getLineInfoByOrgCodeAndLineCodeNumber(entrustReasonRecord.getClientOrgCode(), null, entrustReasonRecord.getClientLineCode()) :
                sysDepartParamService.getLineInfoByOrgCodeAndLineCodeNumber(caseMainInfo.getCaseOrgCode(), caseMainInfo.getCaseDeptCode(), caseMainInfo.getLineCode());
        // 获取条线信息
        String lineDocNumber = lineTerritoryInfoVo.getLineDocNumber();
        //获取（ ）内的内容 如立案、移案、询通、调证、登保决、鉴聘、申避决、听通、当罚决、不罚决、行罚决、行罚缴决、强执决、代履决、强执申、电送确、终决等；
        ConfigBusiParamDocumentInfo configBusiParamDocumentInfo = configBusiParamDocumentInfoService.getDetailByDocumentCatalogCode(documentCatalogCode);
        String numAbbreviation = configBusiParamDocumentInfo.getDocumentNumberAbbreviation();
        //获取年度 “〔 〕”处填写年度
        String curretYear = "";
        //生态环境条线若跨年，以审批通过的年份为准
        if (StringUtils.isNotBlank(caseMainInfo.getCaseNumber()) && !TerritoryCodeEnum.STHJ.getCode().equals(caseMainInfo.getCaseTerritoryCode())) {
            curretYear = caseMainInfo.getCaseNumber().substring(caseMainInfo.getCaseNumber().indexOf("〔"), caseMainInfo.getCaseNumber().indexOf("〕") + 1);
        } else {
            curretYear = "〔" + String.valueOf(LocalDate.now().getYear()) + "〕";
            //curretYear = "〔2023〕";
        }

        //String curretYear = "〔1990〕";
        //“第 号”处填写4位自增序号的顺序编号。从缓存原子中获取
        //String documentNumberKey = "UPCASE-DOCUMENTNUMBERKEY-" + curretYear;
        // long number = redisRepository.incr(documentNumberKey);
        //文书序号类型 1-按时间顺序 2-与某文书一致 3-与某文书一致且重复则二级 4-与某文书使用同一套序列规则 5-按时间顺序,同一案件同一当事人文号不变,重复则二级
        long number=0L;
        String docNumber = "";
        if ("2".equals(configBusiParamDocumentInfo.getDocumentNumberSerialType())) {
            CaseDocumentRecord caseDocumentRecord = caseDocumentRecordService.getCaseDocumentRecord(caseId, configBusiParamDocumentInfo.getDocumentNumberMatchCatalogCode());
            String docNum = caseDocumentRecord.getDocumentNumber();
            if (TerritoryCodeEnum.STHJ.getCode().equals(caseMainInfo.getCaseTerritoryCode())) {
                //生态环境全部文书，去掉文号里面的“第”，数字虚号“00000”
                if (docNum.indexOf("第") != -1) {
                    docNumber = docNum.substring(docNum.indexOf("第") + 1, docNum.length() - 1);
                } else {
                    docNumber = docNum.substring(docNum.indexOf("〕") + 1, docNum.length() - 1);
                }
                docNumber = "" + Integer.valueOf(docNumber);
            } else {
                docNumber = docNum.substring(docNum.indexOf("第") + 1, docNum.length() - 1);
            }
        } else if ("3".equals(configBusiParamDocumentInfo.getDocumentNumberSerialType())) {
            CaseDocumentRecord caseDocumentRecord = caseDocumentRecordService.getCaseDocumentRecord(caseId, configBusiParamDocumentInfo.getDocumentNumberMatchCatalogCode());
            //撤回，也算重复文书
            List<CaseDocumentRecord> caseDocumentRecordList = caseDocumentRecordService.getCaseDocumentRecordListFindNumSerial(caseId, documentCatalogCode);
            /*int sorSerial = 0;
            if(caseDocumentRecordList.size()>0){
                CaseDocumentRecord lastCaseDocumentRecord = caseDocumentRecordList.get(0);
                String lastDocNum = lastCaseDocumentRecord.getDocumentNumber();
                if(lastDocNum.indexOf("-")>0){
                    sorSerial = Integer.parseInt(lastDocNum.substring(lastDocNum.indexOf("-"),lastDocNum.length()-1));
                }
            }*/

            String docNum = caseDocumentRecord.getDocumentNumber();
            if (TerritoryCodeEnum.STHJ.getCode().equals(caseMainInfo.getCaseTerritoryCode())) {
                //生态环境全部文书，去掉文号里面的“第”，数字虚号“00000”
                if (docNum.indexOf("第") != -1) {
                    docNumber = docNum.substring(docNum.indexOf("第") + 1, docNum.length() - 1);
                } else {
                    docNumber = docNum.substring(docNum.indexOf("〕") + 1, docNum.length() - 1);
                }
                docNumber = "" + Integer.valueOf(docNumber);
            } else {
                docNumber = docNum.substring(docNum.indexOf("第") + 1, docNum.length() - 1);
            }
            //TODO 还要考虑下该文书是审批前生成文号，还是审批后生成文号，目前只考虑了审批后生成的文书，所以没有加1，因为文书会在审批前就生成
            if ("3".equals(caseMainInfo.getCasePartiesReasonType()) && "2".equals(caseMainInfo.getHandleType())) {
                int smallSerial = caseDocumentRecordList.size() + 1;
                docNumber = docNumber + "-" + smallSerial;
            } else {
                if (caseDocumentRecordList.size() > 0) {
                    docNumber = docNumber + "-" + caseDocumentRecordList.size();
                }
            }
        } else {
            if ("4".equals(configBusiParamDocumentInfo.getDocumentNumberSerialType())) {
                //4-与某文书使用相同序列
                documentCatalogCode = configBusiParamDocumentInfo.getDocumentNumberMatchCatalogCode();
            }
            String orgCode = caseMainInfo.getCaseOrgCode();
            String deptCode = caseMainInfo.getCaseDeptCode();
            String lineCode = caseMainInfo.getLineCode();
            //获取委托组织code
            if (Objects.nonNull(entrustReasonRecord)) {
                orgCode = entrustReasonRecord.getClientOrgCode();
                lineCode = entrustReasonRecord.getClientLineCode();
                deptCode = null;
            }
            number = caseDocumentNumberSerialService.getNumber(caseId, "CASE", documentCatalogCode, orgCode, deptCode, lineCode, curretYear);
            docNumber = String.format("%06d", number);
            if (TerritoryCodeEnum.STHJ.getCode().equals(caseMainInfo.getCaseTerritoryCode())) {
                //生态环境全部文书，去掉文号里面的“第”，数字虚号“00000”
                docNumber = "" + number;
            }
        }
        //String documentNumber = docDeptShort + "（" + numAbbreviation + "）" + curretYear + String.format("%06d", number);
        String documentNumber = lineDocNumber + numAbbreviation + curretYear + "第" + docNumber + "号";
        if (TerritoryCodeEnum.NYNC.getCode().equals(caseMainInfo.getCaseTerritoryCode()) && Objects.isNull(entrustReasonRecord)) {
            //农业农村文号生成规则：行政机关简称+（条线类别）+文书简称+〔年份〕+序号
            String lineTypeName = caseMainInfo.getLineTypeName();
            documentNumber = lineDocNumber + "（" + lineTypeName + "）" + numAbbreviation + curretYear + "第" + docNumber + "号";
        } else if (TerritoryCodeEnum.STHJ.getCode().equals(caseMainInfo.getCaseTerritoryCode())) {
            //生态环境文号生成规则：生态环境全部文书，去掉文号里面的“第”，数字虚号“00000”
            documentNumber = lineDocNumber + numAbbreviation + curretYear + docNumber + "号";
        }
        resultMap.put("documentNumber",documentNumber);//文号
        if(number!=0){
            resultMap.put("serialNumber",number);//序号
        }
        return resultMap;
    }


    /**
     * 委托事项 获取委托单位组织code，如果存在的情况下。
     *
     * @param caseId
     * @param caseMainInfo
     * @return
     */
    private String getEntrustClientOrgCodeIfExists(String caseId, CaseMainInfo caseMainInfo) {
        CaseReasonMainRecord reasonRecord = getEntrustCaseReasonIfExists(caseId, caseMainInfo);
        if (Objects.isNull(reasonRecord)) {
            return null;
        }
        return reasonRecord.getClientOrgCode();
    }

    /**
     * 获取委托案件，案件原因如果存在
     *
     * @param caseId       案件id
     * @param caseMainInfo 案件信息
     * @return
     */
    private CaseReasonMainRecord getEntrustCaseReasonIfExists(String caseId, CaseMainInfo caseMainInfo) {
        Example caseReasonMainRecordExample = new Example(CaseReasonMainRecord.class);
        caseReasonMainRecordExample.createCriteria().andEqualTo("caseId", caseId).andEqualTo("sxType", "4");
        List<CaseReasonMainRecord> caseReasonMainRecords = caseReasonMainRecordMapper.selectByExample(caseReasonMainRecordExample);
        //当简易程序 && 有委托执法事项时，取委托单位的组织code查询
        if (CaseTypeEnum.SIMPLE_PROCEDURE.getCode().equals(caseMainInfo.getCaseType()) && CollUtil.isNotEmpty(caseReasonMainRecords)) {
            return caseReasonMainRecords.get(Constant.INTEGER_0);
        }
        return null;
    }

    /**
     * 生成预览文书
     *
     * @param saveDto
     * @return {@link Map< String, Object>}
     * @author liyafeng
     * @date 2022/3/30
     */
    @Override
    public Map<String, Object> genPreviewDoc(StageDocCommonPreviewDto saveDto) {
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("success", "true");
        resultMap.put("msg", "文书生成成功！");
        String templateCode = saveDto.getDocumentTemplateCode();
        ConfigBusiParamDocumentInfo detailResult = configBusiParamDocumentInfoService.getDetailByDocumentCatalogCode(saveDto.getDocumentCatalogCode());
        HashMap<String, Object> dataMap = saveDto.getDataMap();
        if (ObjectUtil.isEmpty(templateCode)) {
            if (ObjectUtil.isNotEmpty(saveDto.getCaseId())) {
                templateCode = getTemplateCodeByDocumentCatalogCode(saveDto.getDocumentCatalogCode(), saveDto.getCaseId(), null, saveDto.getPartyId());
            } else {
                templateCode = detailResult.getTemplatePersonCode();
            }
        }

        if (DocumentKindEnum.DOC_KIND_DK1TZDSRNBSPB.getCode().equals(detailResult.getDocumentKindCode())) {
            CaseMainInfoVo caseMainInfoVo = caseMainInfoService.getCaseMainInfo(saveDto.getCaseId());
            CasePartyRecordAdjustSaveDto casePartyRecordAdjustSaveDto = JSONObject.toJavaObject((JSON) JSONObject.toJSON(saveDto.getDataMap()), CasePartyRecordAdjustSaveDto.class);
            caseInfoAdjustRecordService.checkAndAssembleAdjustPartyRecordParam(caseMainInfoVo, casePartyRecordAdjustSaveDto);
            dataMap = BaseUtil.javaToMap(casePartyRecordAdjustSaveDto);
        }
        //生成未签章文书
        FillAndConvertToPdfRequest pdfRequest = new FillAndConvertToPdfRequest();
        pdfRequest.setTemplateCode(templateCode);
        pdfRequest.setParamMap(dataMap);
        pdfRequest.setTemplateType(saveDto.getTemplateType());
        Map<String, String> pdfUrlMap = getConvertedPdfUrl(pdfRequest);
        if (ObjectUtil.isEmpty(pdfUrlMap)) {
            resultMap.put("success", "false");
            resultMap.put("msg", "文书生成失败！");
            return resultMap;
        }
        String pdfUrl = pdfUrlMap.get("fileUrl");
        resultMap.put("pdfUrl", pdfUrl);
        return resultMap;
    }

    @Override
    public Result<Map<String, Object>> rebuildPdf(Map<String, Object> paramJson) {
        List<String> errorDocumentId = new ArrayList<>();
        int num = 0;
        String documentType = ObjectUtils.isEmpty(paramJson.get("documentType")) ? "" : paramJson.get("documentType").toString();
        if (ObjectUtil.isNotEmpty(paramJson.get("documentInfo"))) {
            List<Map> documentInfos = JSON.parseArray(JSON.toJSONString(paramJson.get("documentInfo")), Map.class);
            // 1、普通程序
            if (ObjectUtil.isEmpty(documentType) || "PTCX".equals(documentType)) {
                for (Map documentInfo : documentInfos) {
                    try {
                        CaseDocumentRecordVo documentRecordVo = caseDocumentRecordService.getCaseDocumentRecordInfo(documentInfo.get("documentId").toString());
                        String documentContent = documentRecordVo.getDocumentContent();
                        Map<String, Object> jsonObject = JSON.parseObject(documentContent);

                        String templateCode = getTemplateCodeByDocumentCatalogCode(documentRecordVo.getDocumentCatalogCode(), documentRecordVo.getCaseId(), jsonObject, documentRecordVo.getPartyId());
                        FillAndConvertToPdfRequest relatePdfRequest = new FillAndConvertToPdfRequest();
                        relatePdfRequest.setTemplateCode(templateCode);
                        if (ObjectUtil.isNotEmpty(documentRecordVo.getDocumentTemplateType())
                                && documentRecordVo.getDocumentTemplateType().equals(DocumentTemplateTypeEnum.NARROW_TEMPLATE.getCode())) {
                            relatePdfRequest.setTemplateType("narrow");
                        } else {
                            relatePdfRequest.setTemplateType("standard");
                        }
                        relatePdfRequest.setParamMap(jsonObject);
                        Map<String, String> docPdfUrl = getConvertedPdfUrl(relatePdfRequest);
                        CaseDocumentRecord updateCaseDocumentRecord = new CaseDocumentRecord();
                        updateCaseDocumentRecord.setId(documentRecordVo.getId());
                        updateCaseDocumentRecord.setDocumentUrl(docPdfUrl.get("fileUrl"));
                        caseDocumentRecordMapper.updateByPrimaryKeySelective(updateCaseDocumentRecord);
                        if (ObjectUtil.isNotEmpty(documentRecordVo.getDocumentUrlAfterSeal())) {
                            FileSealInfoQueryDto queryDto = new FileSealInfoQueryDto();

                            if (ObjectUtil.isNotEmpty(documentInfo.get("uniscid"))) {
                                queryDto.setUniscid(documentInfo.get("uniscid").toString());
                            } else {
                                CaseMainInfoVo caseMainInfo = caseMainInfoService.getCaseMainInfo(documentRecordVo.getCaseId());
                                SysDepartParam sysDepartParam = sysDepartParamService.getSysDepartParamByOrgCode(caseMainInfo.getCaseOrgCode(), caseMainInfo.getCaseDeptCode());
                                queryDto.setUniscid(sysDepartParam.getUnicode());
                            }

                            queryDto.setFileBase64(docPdfUrl.get("fileBase64"));
                            CaseMainInfo caseMainInfo = caseMainInfoMapper.selectByPrimaryKey(documentRecordVo.getCaseId());
                            queryDto.setDeptCode(caseMainInfo.getCaseDeptCode());
                            String relatePdfSealUrl = dealFileSeal(queryDto);
                            updateCaseDocumentRecord.setDocumentUrlAfterSeal(relatePdfSealUrl);
                            caseDocumentRecordMapper.updateByPrimaryKeySelective(updateCaseDocumentRecord);
                        }
                        num++;
                    } catch (Exception e) {
                        errorDocumentId.add(documentInfo.get("documentId").toString());
                        e.printStackTrace();
                        log.info("更新文书失败，documentId：{},result:{}", documentInfo.get("documentId").toString(), e.getMessage());
                    }
                }
            } else {
                //4、案源登记
                if ("AY".equals(documentType)) {
                    for (Map documentInfo : documentInfos) {
                        try {
                            String documentId = documentInfo.get("documentId").toString();
                            CaseSourceDocumentRecord documentRecord = caseSourceDocumentRecordMapper.selectByPrimaryKey(documentId);
                            FillAndConvertToPdfRequest relatePdfRequest = new FillAndConvertToPdfRequest();
                            String templateCode = "";
                            if (ObjectUtil.isNotEmpty(documentInfo.get("templateCode"))) {
                                templateCode = documentInfo.get("templateCode").toString();
                            } else {
                                templateCode = sourceDocCommonOperateService.getTemplateCodeByDocumentCatalogCode(documentRecord.getDocumentCatalogCode(), documentRecord.getCaseSourceId(), null);

                            }
                            relatePdfRequest.setTemplateCode(templateCode);
                            Map<String, Object> jsonObject = JSON.parseObject(documentRecord.getDocumentContent());
                            relatePdfRequest.setParamMap(jsonObject);
                            Map<String, String> docPdfUrl = getConvertedPdfUrl(relatePdfRequest);
                            CaseSourceDocumentRecord updateRecord = new CaseSourceDocumentRecord();
                            updateRecord.setId(documentRecord.getId());
                            updateRecord.setDocumentUrl(docPdfUrl.get("fileUrl"));
                            caseSourceDocumentRecordMapper.updateByPrimaryKeySelective(updateRecord);
                            num++;
                        } catch (Exception e) {
                            errorDocumentId.add(documentInfo.get("documentId").toString());
                            e.printStackTrace();
                            log.info("更新文书失败，documentId：{},result:{}", documentInfo.get("documentId").toString(), e.getMessage());
                        }
                    }
                }
                //2、简易程序
                if ("JYCX".equals(documentType)) {
                    for (Map documentInfo : documentInfos) {
                        try {
                            CaseDocumentRecordVo documentRecordVo = caseDocumentRecordService.getCaseDocumentRecordInfo(documentInfo.get("documentId").toString());
                            String documentContent = documentRecordVo.getDocumentContent();
                            Map<String, Object> jsonObject = JSON.parseObject(documentContent);
                            String templateCode = getTemplateCodeByDocumentCatalogCode(documentRecordVo.getDocumentCatalogCode(), documentRecordVo.getCaseId(), jsonObject, documentRecordVo.getPartyId());
                            FillAndConvertToPdfRequest relatePdfRequest = new FillAndConvertToPdfRequest();
                            relatePdfRequest.setTemplateCode(templateCode);
                            relatePdfRequest.setTemplateType("narrow");

                            relatePdfRequest.setParamMap(jsonObject);
                            Map<String, String> docPdfUrl = getConvertedPdfUrl(relatePdfRequest);
                            CaseDocumentRecord updateCaseDocumentRecord = new CaseDocumentRecord();
                            updateCaseDocumentRecord.setId(documentRecordVo.getId());
                            updateCaseDocumentRecord.setDocumentUrl(docPdfUrl.get("fileUrl"));
                            caseDocumentRecordMapper.updateByPrimaryKeySelective(updateCaseDocumentRecord);
                            if (ObjectUtil.isNotEmpty(documentRecordVo.getDocumentUrlAfterSeal())) {
                                //现场照片说明不用签章
                                if ("DC2A0223300XCZPJSM000000001".equals(documentRecordVo.getDocumentCatalogCode())) {
                                    updateCaseDocumentRecord.setDocumentUrlAfterSeal(updateCaseDocumentRecord.getDocumentUrl());
                                    if (ObjectUtil.isNotEmpty(documentRecordVo.getDocumentUrlAfterSign())) {
                                        updateCaseDocumentRecord.setDocumentUrlAfterSign(updateCaseDocumentRecord.getDocumentUrl());
                                    }
                                } else {
                                    CaseMainInfo caseMainInfo = caseMainInfoMapper.selectByPrimaryKey(documentRecordVo.getCaseId());
                                    FileSealInfoQueryDto queryDto = new FileSealInfoQueryDto();
                                    queryDto.setUniscid(documentInfo.get("uniscid").toString());
                                    queryDto.setFileBase64(docPdfUrl.get("fileBase64"));
                                    queryDto.setDeptCode(caseMainInfo.getCaseDeptCode());
                                    String relatePdfSealUrl = dealFileSeal(queryDto);
                                    updateCaseDocumentRecord.setDocumentUrlAfterSeal(relatePdfSealUrl);
                                    if (ObjectUtil.isNotEmpty(documentRecordVo.getDocumentUrlAfterSign())) {
                                        updateCaseDocumentRecord.setDocumentUrlAfterSign(relatePdfSealUrl);
                                    }
                                }
                                caseDocumentRecordMapper.updateByPrimaryKeySelective(updateCaseDocumentRecord);
                            }
                            num++;
                        } catch (Exception e) {
                            errorDocumentId.add(documentInfo.get("documentId").toString());
                            e.printStackTrace();
                            log.info("更新文书失败，documentId：{},result:{}", documentInfo.get("documentId").toString(), e.getMessage());
                        }
                    }
                }

                //3、办案直通车
                if ("BAZTC".equals(documentType)) {
                    if (ObjectUtil.isEmpty(paramJson.get("templateCode"))) {
                        throw new BusinessException("办案直通车文书templateCode不能为空");
                    }
                    for (Map documentInfo : documentInfos) {
                        try {
                            String documentId = documentInfo.get("documentId").toString();
                            AppCaseBeforeDocumentRecord documentRecordVo = appCaseBeforeDocumentRecordMapper.selectByPrimaryKey(documentId);
                            String documentContent = documentRecordVo.getDocumentContent();
                            Map<String, Object> jsonObject = JSON.parseObject(documentContent);
                            String templateCode = paramJson.get("templateCode").toString();
                            FillAndConvertToPdfRequest relatePdfRequest = new FillAndConvertToPdfRequest();
                            relatePdfRequest.setTemplateCode(templateCode);
                            relatePdfRequest.setTemplateType("narrow");
                            relatePdfRequest.setParamMap(jsonObject);
                            Map<String, String> docPdfUrl = getConvertedPdfUrl(relatePdfRequest);
                            AppCaseBeforeDocumentRecord updateCaseDocumentRecord = new AppCaseBeforeDocumentRecord();
                            updateCaseDocumentRecord.setId(documentRecordVo.getId());
                            updateCaseDocumentRecord.setDocumentUrl(docPdfUrl.get("fileUrl"));
                            appCaseBeforeDocumentRecordMapper.updateByPrimaryKeySelective(updateCaseDocumentRecord);
                            if (ObjectUtil.isNotEmpty(documentRecordVo.getDocumentUrlAfterSeal())) {
                                FileSealInfoQueryDto queryDto = new FileSealInfoQueryDto();
                                queryDto.setUniscid(documentInfo.get("uniscid").toString());
                                queryDto.setFileBase64(docPdfUrl.get("fileBase64"));
                                String relatePdfSealUrl = dealFileSeal(queryDto);
                                updateCaseDocumentRecord.setDocumentUrlAfterSeal(relatePdfSealUrl);
                                if (ObjectUtil.isNotEmpty(documentRecordVo.getDocumentUrlAfterSign())) {
                                    updateCaseDocumentRecord.setDocumentUrlAfterSign(relatePdfSealUrl);
                                }
                                appCaseBeforeDocumentRecordMapper.updateByPrimaryKeySelective(updateCaseDocumentRecord);
                            }
                            num++;
                        } catch (Exception e) {
                            errorDocumentId.add(documentInfo.get("documentId").toString() + e.getMessage());
                            e.printStackTrace();
                            log.info("更新文书失败，documentId：{},result:{}", documentInfo.get("documentId").toString(), e.getMessage());
                        }
                    }
                }
            }
        }
        if ("JYCX_HANDLEPERSON".equals(documentType)) {
            return modifySimpleCase(paramJson);
        }

        Map<String, Object> result = new HashMap<>();
        result.put("errorDocumentId", errorDocumentId);
        result.put("num", num);
        if (num > 0) {
            return Result.success(result);
        } else {
            return Result.error(JSONObject.toJSONString(result));
        }
    }
    /*@Autowired
    public void setRedisRepository(RedisRepository redisRepository) {
        this.redisRepository = redisRepository;
    }*/


    /**
     * @Author: zhengqiang
     * @Date: 2022/5/11
     * @Description: 文书预览接口
     * @param: saveDto
     * @return: {@link Map<String,Object>}
     **/
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Map<String, Object> getDocPreview(StageDocCommonOperateSaveDto saveDto) {
        Map<String, Object> resultMap = new HashMap<>();
        UserDTO userInfo = UserUtil.getUserInfo();
        if (userInfo == null) {
            resultMap.put("msg", "未登录或登录信息已失效");
            resultMap.put("success", false);
            return resultMap;
        }
        //根据文书目录编码获取模板code
        String templateCode = getTemplateCodeByDocumentCatalogCode(saveDto.getDocumentCatalogCode(), saveDto.getCaseId(), saveDto.getDataMap(), saveDto.getPartyId());
        //生成未签章文书
        FillAndConvertToPdfRequest pdfRequest = new FillAndConvertToPdfRequest();
        pdfRequest.setTemplateCode(templateCode);
        pdfRequest.setParamMap(saveDto.getDataMap());
        Map<String, String> pdfUrl = getConvertedPdfUrl(pdfRequest);
        if (ObjectUtil.isEmpty(pdfUrl)) {
            resultMap.put("success", false);
            resultMap.put("msg", "文书生成失败！");
            return resultMap;
        } else {
            resultMap.put("msg", "成功");
            resultMap.put("success", true);
            resultMap.put("fileUrl", pdfUrl.get("fileUrl"));
        }

        return resultMap;
    }


    /**
     * 描述：处理特殊文书
     *
     * @author shishengyao
     * @date 2022/05/25
     */
    public void dealSpecialDocument(StageDocCommonOperateSaveDto saveDto) {
        // 案件暂存操作对应文书参数校验
        if (CaseStatusChangeTypeEnum.isCaseChangeDocEnum(saveDto.getDocumentKindCode())) {
            if (CaseStatusChangeTypeEnum.SUSPEND.getDocumentKindCode().equals(saveDto.getDocumentKindCode())) {
                saveDto.setIsMultipleDoc(Constant.STRING_1);
                CaseMainInfoStatusChangeRecord changeRecord = caseMainInfoStatusChangeRecordService.getCaseMainInfoStatusChangeRecordByChangeType(saveDto.getCaseId(), CaseStatusChangeTypeEnum.SUSPEND.getCode());
                if (ObjectUtil.isNotEmpty(changeRecord) && CaseStatusChangeEffectEnum.INVALID.getCode().equals(changeRecord.getStatus())) {
                    saveDto.setBelongDocumentId(changeRecord.getDocumentId());
                } else {
                    saveDto.setBelongDocumentId(null);
                }

            }
        }
        //更正公示
        if (DocumentKindEnum.DOC_KIND_DT1SQGZGSSPB.getCode().equals(saveDto.getDocumentKindCode())) {
            saveDto.setIsMultipleDoc(Constant.STRING_1);
            CasePublicityModifyRecord modifyRecord = casePublicityModifyRecordService.getLastPublicityModifyRecord(saveDto.getCaseId(), saveDto.getPartyId(), CasePublicityModifyEnum.CORRECT_PUBLICITY.getCode());
            if (ObjectUtil.isNotEmpty(modifyRecord)
                    && Constant.STRING_0.equals(modifyRecord.getStatus())) {
                saveDto.setBelongDocumentId(modifyRecord.getDocumentId());
            } else {
                saveDto.setBelongDocumentId(null);
            }
        }
        //处理人社授权委托书
        if ("DC2A0173300SQWTS00000000001".equals(saveDto.getDocumentCatalogCode())) {
            Map<String, Object> dataMap = saveDto.getDataMap();
            //先无效原有授权委托书
            caseDocumentAuthedEntrustMapper.updateDocumentAuthedEntrustStatus(saveDto.getCaseId());
            //新增授权委托书
            CaseDocumentAuthedEntrust caseDocumentAuthedEntrust = new CaseDocumentAuthedEntrust();
            caseDocumentAuthedEntrust.setId(StringUtils.uuid());
            caseDocumentAuthedEntrust.setStatus(Constant.INTEGER_1);
            caseDocumentAuthedEntrust.setCaseId(saveDto.getCaseId());
            caseDocumentAuthedEntrust.setPartyId(saveDto.getPartyId());
            //String jsonArrayStr=MapUtils.getString(dataMap,"attachment","");
            caseDocumentAuthedEntrust.setAppendixUrl(MapUtils.getString(dataMap, "attachment", ""));
            caseDocumentAuthedEntrust.setEntrustName(MapUtils.getString(dataMap, "entrustName", ""));
            String authedName = MapUtils.getString(dataMap, "authedName", "");
            if (StringUtils.isNotBlank(MapUtils.getString(dataMap, "authedName2", ""))) {
                authedName = authedName + "、" + MapUtils.getString(dataMap, "authedName2", "");
            }
            caseDocumentAuthedEntrust.setAuthedName(authedName);
            String authedMobile = MapUtils.getString(dataMap, "authedMobile", "");
            if (StringUtils.isNotBlank(MapUtils.getString(dataMap, "authedMobile2", ""))) {
                authedMobile = authedMobile + "、" + MapUtils.getString(dataMap, "authedMobile2", "");
            }
            caseDocumentAuthedEntrust.setAuthedMobile(authedMobile);
            String authedCertNo = MapUtils.getString(dataMap, "authedCertNo", "");
            if (StringUtils.isNotBlank(MapUtils.getString(dataMap, "authedCertNo2", ""))) {
                authedCertNo = authedCertNo + "、" + MapUtils.getString(dataMap, "authedCertNo2", "");
            }
            caseDocumentAuthedEntrust.setAuthedCertNo(authedCertNo);
            caseDocumentAuthedEntrustMapper.insert(caseDocumentAuthedEntrust);
        }
        //处理移动端普通程序-询问通知书逻辑
        dealAppAskNotifyDocument(saveDto);
    }

    /**
     * 处理移动端普通程序-询问通知书逻辑
     *
     * @param saveDto
     */
    private void dealAppAskNotifyDocument(StageDocCommonOperateSaveDto saveDto) {
        //判断文书模板号是否为移动端普通程序-询问通知书
        if (!"APPDT2XWTZS00000000002".equals(saveDto.getDocumentTemplateCode())) {
            return;
        }
        CaseMainDetailInfo caseMainDetailInfo = caseMainDetailInfoMapper.selectByPrimaryKey(saveDto.getCaseId());
        HashMap<String, Object> dataMap = saveDto.getDataMap();
        //设置询问地址
        caseMainDetailInfo.setAcceptInquireAddress(MapUtil.getStr(dataMap, "xwtzs_xwdz"));
        //设置携带资料
        caseMainDetailInfo.setAcceptInquireCarryMaterial(dealAskNoticeAcceptInquireCarryMaterial(dataMap));
        //设置接受询问日期
        String acceptInquireTimeStr = MapUtil.getStr(dataMap, "xwtzs_jsxwsj");
        LocalDateTime acceptInquireTime = null;
        String dateFormat = "yyyy年MM月dd日HH时mm分ss秒";
        try {
            acceptInquireTime = cn.hutool.core.date.DateUtil.parseLocalDateTime(acceptInquireTimeStr, dateFormat);
        } catch (Exception e) {
            log.error("日期转换失败=>无法以【{}】格式转换日期【{}】", dateFormat, acceptInquireTimeStr);
        }
        caseMainDetailInfo.setAcceptInquireTime(acceptInquireTime);
        caseMainDetailInfo.setInquireDocGenerateTime(LocalDateTime.now());
        //保存询问通知书的信息到案件信息中
        caseMainDetailInfoMapper.updateByPrimaryKeySelective(caseMainDetailInfo);
    }

    /**
     * 处理 询问通知的询问携带资料
     *
     * @param askNoticeDataMap
     * @return
     */
    private String dealAskNoticeAcceptInquireCarryMaterial(HashMap<String, Object> askNoticeDataMap) {
        //携带资料集合
        List<String> materials = new LinkedList<>();
        //循环获取需要携带资料
        buildAskNoticeMaterialFieldMap().forEach((key, value) -> {
            if (!Boolean.TRUE.equals(MapUtil.getBool(askNoticeDataMap, key))) {
                return;
            }
            materials.add(value);
        });
        //其他材料详情
        String otherFileDetail = MapUtil.getStr(askNoticeDataMap, "XWTZS_ZF_QTCL_XQ");
        if (StrUtil.isNotEmpty(otherFileDetail)) {
            materials.add(otherFileDetail);
        }
        return CollUtil.join(materials, ",");
    }

    /**
     * 构建询问通知书携带资料字段集合
     *
     * @return 通知书携带资料字段集合
     */
    private Map<String, String> buildAskNoticeMaterialFieldMap() {
        Map<String, String> map = new HashMap<>();
        map.put("xwtzs_yyzz", "营业执照");
        map.put("xwtzs_zzjgdmz", "组织机构代码证");
        map.put("xwtzs_fddbrzs", "法定代表人或负责人身份证及身份证明书");
        map.put("xwtzs_brsfzj", "本人身份证或其他有效证件");
        map.put("xwtzs_sqwts", "授权委托书");
        map.put("xwtzs_xgxkzj", "相关许可证件");
        map.put("xwtzs_otherfile", "其他材料");
        return map;
    }

    /**
     * 描述：处理案件状态操作变更
     *
     * @author shishengyao
     * @date 2022/05/25
     */
    public void updateCaseStatusChange(StageDocCommonOperateSaveDto saveDto, String
            documentId, ConfigBusiParamDocumentInfo configBusiParamDocumentInfo) {
        if (ObjectUtil.isEmpty(saveDto.getDocumentKindCode())) {
            throw new BusinessException("文书种类不能为空");
        }
        String documentKindCode = saveDto.getDocumentKindCode();
        if (CaseStatusChangeTypeEnum.isCaseChangeDocEnum(documentKindCode)) {
            CaseStatusChangeTypeEnum caseStatusChangeTypeEnum = CaseStatusChangeTypeEnum.getEnumByDocumentKindCode(saveDto.getDocumentKindCode());
            String operateType = caseStatusChangeTypeEnum.getCode();
            CaseOperateUpdateDto operateSaveDto = new CaseOperateUpdateDto();
            operateSaveDto.setDocumentId(documentId);
            operateSaveDto.setCaseId(saveDto.getCaseId());
            operateSaveDto.setDataMap(saveDto.getDataMap());
            operateSaveDto.setDocumentKindCode(saveDto.getDocumentKindCode());
            operateSaveDto.setDocumentCatalogCode(saveDto.getDocumentCatalogCode());
            operateSaveDto.setAppendixList(saveDto.getAppendixList());
            operateSaveDto.setCaseOperateType(caseStatusChangeTypeEnum.getCode());

            CaseMainInfoStatusChangeRecord changeRecord = caseMainInfoStatusChangeRecordService.getCaseMainInfoStatusChangeRecordByChangeType(saveDto.getCaseId(), operateType);
            if (ObjectUtil.isEmpty(changeRecord)) {
                caseMainInfoStatusChangeRecordService.saveCaseChangeOperate(operateSaveDto);
            } else {
                if (ObjectUtil.isEmpty(saveDto.getDocumentApprovalStatus())) {
                    CaseDocumentRecord caseDocumentRecord = caseDocumentRecordMapper.selectByPrimaryKey(changeRecord.getDocumentId());
                    if (!ObjectUtils.isEmpty(caseDocumentRecord)) {
                        if (caseDocumentRecord.getDocumentApprovalStatus().equals(DocumentStatusEnum.CHECKING.getCode()) && !DocumentRecordStatusEnum.WITHDRAW.getCode().equals(caseDocumentRecord.getDocumentRecordStatus())) {
                            throw new BusinessException("已有在审批的" + caseStatusChangeTypeEnum.getDes() + "文书，请勿重复提交！");
                        } else {
                            caseMainInfoStatusChangeRecordService.saveCaseChangeOperate(operateSaveDto);
                        }
                    }

                }
            }
        }
        //公示管理文书
        if (DocumentKindEnum.DOC_KIND_DT1SQGZGSSPB.getCode().equals(documentKindCode)
                || DocumentKindEnum.DOC_KIND_DT1SQCXGSSPB.getCode().equals(documentKindCode)) {
            CaseDocumentRecord caseDocumentRecord = caseDocumentRecordMapper.selectByPrimaryKey(documentId);
            if (!DocumentStatusEnum.CHECK_END.getCode().equals(caseDocumentRecord.getDocumentApprovalStatus())) {
                PublicityModifyRecordSaveDto modifyRecordSaveDto = new PublicityModifyRecordSaveDto();
                modifyRecordSaveDto.setCaseId(saveDto.getCaseId());
                modifyRecordSaveDto.setDocumentId(documentId);
                modifyRecordSaveDto.setPartyId(saveDto.getPartyId());
                modifyRecordSaveDto.setDataMap(saveDto.getDataMap());
                modifyRecordSaveDto.setDocumentKindCode(documentKindCode);
                casePublicityModifyRecordService.saveCasePublicityModifyRecord(modifyRecordSaveDto);
            }
        }

    }

    /**
     * 获取APP直通车文书文号
     *
     * @param busiId
     * @param documentKindCode
     * @param lineCode
     * @return
     */
    @Override
    public String getDocumentNumberForAppCar(String busiId, String documentKindCode, String lineCode, String lineTypeCode) {
        UserDTO userDTO = UserUtil.getUserInfo();
        String orgCode = userDTO.getOrgCode();
        String deptCode = userDTO.getDeptCode();
        //获取办案条线对应的领域
        LineDTO lineDTO = xzzfInterfaceService.getLineInfoByLineCode(lineCode);
        String territoryCode = lineDTO.getTerritoryCode();
        // 获取条线信息
        LineTerritoryInfoVo lineTerritoryInfoVo = sysDepartParamService.getLineInfoByOrgCodeAndLineCodeNumber(orgCode, deptCode, lineCode);
        String lineDocNumber = lineTerritoryInfoVo.getLineDocNumber();

        //获取领域下业务参数
        RelationWorkflowInfoRequest request = new RelationWorkflowInfoRequest();
        request.setApplyAreaCode(userDTO.getAreaCode());
        request.setApplyFieldCode(territoryCode);
        List<ConfigBusiParamMain> configBusiParamMainList = configBusiParamMainService.getConfigBusiParamMainList(request);
        ConfigBusiParamDocumentInfo configBusiParamDocumentInfo = configBusiParamDocumentInfoService.getDocumentInfoByDocumentKindCode(configBusiParamMainList.get(0).getId(), documentKindCode);
        String documentCatalogCode = configBusiParamDocumentInfo.getDocumentCatalogCode();
        //获取（ ）内的内容 如立案、移案、询通、调证、登保决、鉴聘、申避决、听通、当罚决、不罚决、行罚决、行罚缴决、强执决、代履决、强执申、电送确、终决等；
        configBusiParamDocumentInfo = configBusiParamDocumentInfoService.getDetailByDocumentCatalogCode(documentCatalogCode);
        String numAbbreviation = configBusiParamDocumentInfo.getDocumentNumberAbbreviation();
        //获取年度 “〔 〕”处填写年度
        String curretYear = "〔" + String.valueOf(LocalDate.now().getYear()) + "〕";
        long number;
        String docNumber = "";
        if ("4".equals(configBusiParamDocumentInfo.getDocumentNumberSerialType())) {
            //4-与某文书使用相同序列
            documentCatalogCode = configBusiParamDocumentInfo.getDocumentNumberMatchCatalogCode();
        }
        number = caseDocumentNumberSerialService.getNumber(busiId, "CASE", documentCatalogCode, orgCode, deptCode, lineCode, curretYear);
        docNumber = String.format("%06d", number);
        if (TerritoryCodeEnum.STHJ.getCode().equals(territoryCode)) {
            //生态环境全部文书，去掉文号里面的“第”，数字虚号“00000”
            docNumber = "" + number;
        }
        String documentNumber = lineDocNumber + numAbbreviation + curretYear + "第" + docNumber + "号";
        if (TerritoryCodeEnum.NYNC.getCode().equals(territoryCode)) {
            //农业农村文号生成规则：行政机关简称+（条线类别）+文书简称+〔年份〕+序号
            ConfigDictionaryInfo configDictionaryInfo = new ConfigDictionaryInfo();
            configDictionaryInfo.setDicFieldCode("LINE_TYPE");
            configDictionaryInfo.setDicCode(lineTypeCode);
            configDictionaryInfo.setIsEffective("1");
            ConfigDictionaryInfo info = configDictionaryInfoMapper.selectOne(configDictionaryInfo);
            String lineTypeName = info.getDicName();
            documentNumber = lineDocNumber + "（" + lineTypeName + "）" + numAbbreviation + curretYear + "第" + docNumber + "号";
        } else if (TerritoryCodeEnum.STHJ.getCode().equals(territoryCode)) {
            //生态环境文号生成规则：生态环境全部文书，去掉文号里面的“第”，数字虚号“00000”
            documentNumber = lineDocNumber + numAbbreviation + curretYear + docNumber + "号";
        }
        return documentNumber;
    }

    /**
     * 【V1.12.0】描述： 获取处罚内容(普通程序案件, 简易程序案件, 补录案件)
     *
     * @return {@link String}
     * @author: zhengqiang
     * @date: 2023/8/8
     * @param: caseId
     **/
    @Override
    public String getCaseRevokePunishContent(String caseId) {
        //处罚内容
        String punishContent = "";
        CaseMainInfo caseMainInfo = caseMainInfoMapper.selectByPrimaryKey(caseId);
        if (ObjectUtil.isNotEmpty(caseMainInfo)) {
            if (CaseTypeEnum.SIMPLE_PROCEDURE.getCode().equals(caseMainInfo.getCaseType())) {
                //简易程序
                CaseMainDetailSimpleInfo caseMainDetailSimpleInfo = caseMainDetailSimpleInfoService.getCaseMainDetailSimpleInfo(caseId);
                String punishDesc = "罚款人民币" + ConvertUpMoneyUtil.toChinese(caseMainDetailSimpleInfo.getDraftPunishMoney()) + "整（￥" + caseMainDetailSimpleInfo.getDraftPunishMoney() + "）";
                if (caseMainDetailSimpleInfo.getPunishKinds().contains("警告") && caseMainDetailSimpleInfo.getPunishKinds().contains("罚款")) {
                    punishDesc = "警告及" + punishDesc;
                } else if ("警告".equals(caseMainDetailSimpleInfo.getPunishKinds())) {
                    punishDesc = "警告";
                }
                punishContent = punishDesc;
            } else {
                //普通程序
                CaseMainDetailInfo caseMainDetailInfo = caseMainDetailInfoMapper.selectByPrimaryKey(caseId);
                punishContent = caseMainDetailInfo.getPunishContent();
            }
        } else {
            //查询补录案件
            CaseAdditionalRecord caseAdditionalRecord = caseAdditionalRecordService.getCaseAdditionalRecordById(caseId);
            if (ObjectUtil.isNotEmpty(caseAdditionalRecord)) {
                punishContent = caseAdditionalRecord.getPunishContent();
            }
        }
        return punishContent;
    }

    /**
     * 描述：修改简易程序内容【临时修复版本】
     *
     * @param paramJson param json
     * @return {@link Map<String, Object> }
     * @author shishengyao
     * @date 2023/04/26
     */
    @Transactional(rollbackFor = Exception.class)
    public Result<Map<String, Object>> modifySimpleCase(Map<String, Object> paramJson) {
        List<String> errorDocumentId = new ArrayList<>();
        List<String> errorCaseId = new ArrayList<>();
        int num = 0;
        if (ObjectUtil.isNotEmpty(paramJson.get("caseIds"))) {
            String caseIds = (String) paramJson.get("caseIds");
            List<String> caseIdList = Arrays.asList(caseIds.split(","));
            for (String caseId : caseIdList) {
                //查询文书
                List<CaseDocumentRecord> caseDocumentRecordList = caseDocumentRecordService.getCaseDocumentRecordListByCaseId(caseId);
                CaseMainInfoVo caseMainInfo = caseMainInfoService.getCaseMainInfo(caseId);
                //查询办案人员
                List<CaseHandlePersonRecord> caseHandlePersonRecordVoList = caseHandlePersonRecordService.getCaseHandlePersonRecordList(caseId);
                for (CaseDocumentRecord documentRecordVo : caseDocumentRecordList) {
                    try {
                        //添加历史
                        CaseDocumentRecordHis caseDocumentRecordHis = new CaseDocumentRecordHis();
                        BeanUtils.copyProperties(documentRecordVo, caseDocumentRecordHis);
                        caseDocumentRecordHis.setId(StringUtils.uuid());
                        caseDocumentRecordHis.setRecordId(documentRecordVo.getId());
                        caseDocumentRecordHis.setOp("modify");
                        caseDocumentRecordHis.setHisCreateTime(new Date());
                        caseDocumentRecordHisMapper.insert(caseDocumentRecordHis);

                        String documentContent = documentRecordVo.getDocumentContent();
                        Map<String, Object> jsonObject = JSON.parseObject(documentContent);
                        for (CaseHandlePersonRecord handlePersonRecord : caseHandlePersonRecordVoList) {
                            if (ObjectUtil.isNotEmpty(handlePersonRecord.getHandlePersonId())) {
                                if (HandlePersonTypeEnum.MAIN.getCode().equals(handlePersonRecord.getHandlePersonType())) {
                                    jsonObject.put("mainHandleSignPic", handlePersonRecord.getHandleSignPic());
                                    jsonObject.put("mainLawEnforcementCert", handlePersonRecord.getLawEnforcementCert());
                                } else if (HandlePersonTypeEnum.ASSIST.getCode().equals(handlePersonRecord.getHandlePersonType())) {
                                    jsonObject.put("assistHandleSignPic", handlePersonRecord.getHandleSignPic());
                                    jsonObject.put("assistLawEnforcementCert", handlePersonRecord.getLawEnforcementCert());
                                }
                            }
                        }
                        String documentCatalogCode = documentRecordVo.getDocumentCatalogCode();
                        String templateCode = getTemplateCodeByDocumentCatalogCode(documentCatalogCode, documentRecordVo.getCaseId(), jsonObject, documentRecordVo.getPartyId());
                        FillAndConvertToPdfRequest relatePdfRequest = new FillAndConvertToPdfRequest();
                        relatePdfRequest.setTemplateCode(templateCode);

                        ConfigBusiParamDocumentInfo detailResult = configBusiParamDocumentInfoService.getDetailByDocumentCatalogCode(documentCatalogCode);
                        //简易程序是窄幅文书
                        if (DocumentKindEnum.DOC_KIND_JYCXCFJDS.getCode().equals(detailResult.getDocumentKindCode())) {
                            relatePdfRequest.setTemplateType("narrow");
                        } else {
                            relatePdfRequest.setTemplateType("standard");
                        }
                        relatePdfRequest.setParamMap(jsonObject);
                        Map<String, String> docPdfUrl = getConvertedPdfUrl(relatePdfRequest);
                        CaseDocumentRecord updateCaseDocumentRecord = new CaseDocumentRecord();
                        updateCaseDocumentRecord.setId(documentRecordVo.getId());
                        updateCaseDocumentRecord.setDocumentUrl(docPdfUrl.get("fileUrl"));

                        if (ObjectUtil.isNotEmpty(documentRecordVo.getDocumentUrlAfterSeal())) {
                            String relatePdfSealUrl = docPdfUrl.get("fileUrl");
                            //只处理当场处罚决定书
                            if (DocumentKindEnum.DOC_KIND_JYCXCFJDS.getCode().equals(detailResult.getDocumentKindCode())) {
                                FileSealInfoQueryDto queryDto = new FileSealInfoQueryDto();
                                String uniscid = getUniscidByOrgCode(caseMainInfo.getCaseOrgCode(), caseMainInfo.getCaseDeptCode());
                                queryDto.setUniscid(uniscid);
                                queryDto.setFileBase64(docPdfUrl.get("fileBase64"));
                                queryDto.setDeptCode(caseMainInfo.getCaseDeptCode());
                                relatePdfSealUrl = dealFileSeal(queryDto);
                            }
                            updateCaseDocumentRecord.setDocumentUrlAfterSeal(relatePdfSealUrl);
                            updateCaseDocumentRecord.setDocumentContent(JSONObject.toJSONString(jsonObject));
                            if (ObjectUtil.isNotEmpty(documentRecordVo.getDocumentUrlAfterSign())) {
                                updateCaseDocumentRecord.setDocumentUrlAfterSign(relatePdfSealUrl);
                            }
                        }
                        caseDocumentRecordMapper.updateByPrimaryKeySelective(updateCaseDocumentRecord);
                        num++;
                    } catch (Exception e) {
                        errorDocumentId.add(documentRecordVo.getId());
                        errorCaseId.add(caseId);
                        e.printStackTrace();
                        log.info("更新文书失败，caseId,{}documentId：{},result:{}", caseId, documentRecordVo.getId(), e.getMessage());
                    }
                }

            }
        }

        Map<String, Object> result = new HashMap<>();
        result.put("errorDocumentId", errorDocumentId);
        result.put("errorCaseId", errorCaseId);
        result.put("num", num);
        if (num > 0) {
            return Result.success(result);
        } else {
            return Result.error(JSONObject.toJSONString(result));
        }
    }
}
